text: #!/usr/bin/env python3
  # -*- coding:utf-8 -*-
  # author: bigfoolliu
  
  
  from flask import Flask, jsonify, abort, make_response, request, url_for
  from flask_httpauth import HTTPBasicAuth
  from flask_sqlalchemy import SQLAlchemy
  from passlib.apps import custom_app_context as pwd_context
  import task
  
  app = Flask(__name__)
  
  app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///example.sqlite"  # todo:
  db = SQLAlchemy(app)
  
  auth = HTTPBasicAuth()
  
  
  class User(db.Model):
      __tablename__ = 'users'
      id = db.Column(db.Integer, primary_key=True)
      username = db.Column(db.String(32), index=True)
      password_hash = db.Column(db.String(128))
  
      def hash_password(self, password):
          """将密码hash处理"""
          self.password_hash = pwd_context.encrypt(password)
  
      def verify_password(self, password):
          """密码解码"""
          return pwd_context.verify(password, self.password_hash)
  
  
  @app.route('/api/users', methods=['POST'])
  def new_user():
      username = request.json.get('username')
      password = request.json.get('password')
      if username is None or password is None:
          abort(400)  # missing arguments
      if User.query.filter_by(username=username).first() is not None:
          abort(400)  # existing user
      user = User(username=username)
      user.hash_password(password)
      db.session.add(user)
      db.session.commit()
      return jsonify({'username': user.username}), 201, {'Location': url_for('get_user', id=user.id, _external=True)}
  
  
  @auth.get_password
  def get_password(username):
      if username == 'liu':
          return 'python'
      return None
  
  
  @auth.error_handler
  def unauthorized():
      return make_response(jsonify({'error': 'Unauthorized access'}), 403)
  
  
  @app.errorhandler(404)
  def not_found(error):
      return make_response(jsonify({'error': 'Not found'}), 404)
  
  
  if __name__ == '__main__':
      app.run(debug=True)
  