Python make simple registration login system _python

Source: Internet
Author: User

This time I'm mainly explaining how to use Python based flask login and registration to validate using basic Auth

The main use of the following libraries

Import OS
#Flask的基础库 from
flask import flask, abort, request, jsonify, G, url_for
#Flaks的数据库操作的库
from Flask.ext.sqlalchemy Import SQLAlchemy
#Flask登录注册的库 from
flask.ext.httpauth import Httpbasicauth
# Encrypted decryption password library from
passlib.apps import custom_app_context as Pwd_context
#URL安全序列化工具 from
itsdangerous Import (Timedjsonwebsignatureserializer as
             serializer, badsignature, signatureexpired)

First of course is initialized

App = Flask (__name__)
# Set key
app.config[' secret_key ' = ' The quick brown fox jumps over the lazy dog '
# Database The configuration
app.config[' sqlalchemy_database_uri '] = ' sqlite:///db.sqlite '
app.config[' Sqlalchemy_commit_on_ Teardown '] = True

#数据库初始化
db = SQLAlchemy (APP)
# authentication initialization
auth = Httpbasicauth ()

And then the modeling

SQLAlchemy is an ORM model to manipulate the database, so it is very convenient
in addition to the basic attributes we have defined some of the necessary methods

Class User (db. Model):
  __tablename__ = ' users '
  id = db. Column (db. Integer, primary_key=true)
  username = db. Column (db. String (index=true)
  Password_hash = db. Column (db. String ())
  # cryptographic Password
  def hash_password (self, password):
    self.password_hash = pwd_context.encrypt (password
  # Verify Password
  def verify_password (self, password): Return
    pwd_context.verify (password, self.password_hash)
  # Generate token and set expiration Time
  def generate_auth_token (self, expiration=600):
    s = Serializer (app.config[' secret_ KEY '], expires_in=expiration return
    s.dumps ({' id ': self.id})
  # Static Validation token method
  @staticmethod
  def verify_auth_token (token):
    s = Serializer (app.config[' Secret_key '])
    try:
      data = s.loads (token)
    except signatureexpired: return
      None  # token expired
    except badsignature: return
      None  # Token invalid
    user = User.query.get (data[' id ')) return
    user

Registration function

@app. Route ('/api/users ', methods=[' POST ')
def new_user ():
  username = request.json.get (' username ')
  Password = request.json.get (' password ')
  if username is none/password is none:
    abort ()  # User name or password is empty
  If User.query.filter_by (username=username). Not None:
    abort  # users already exist user
  = User (username= username)
  # encrypted password
  user.hash_password (password)
  # saved in database
  db.session.add (user)
  Db.session.commit ()
  # returns the username after successful registration, location followed by a jump address return
  (jsonify ({' username ': User.username}), 201,
      {' Location ': url_for (' Get_user ', Id=user.id, _external=true)})

Login function

# Login to get token
@app. Route ('/api/token ')
@auth. login_required
def get_auth_token ():
  # Set token expiration
  token = G.user.generate_auth_token return
  jsonify ({' token ': Token.decode (' ASCII '), ' Duration ': 600})

After you get the token, you just need to pass token for each request.

We can verify that the token is valid by one method

# you can sign in
@app. Route ('/api/resource ')
@auth. login_required
def get_resource ():
  # by token or account password Returns username return
  jsonify ({' Data ': ' Hello,%s! '% g.user.username}) if token valid

Careful people will find that the above two methods preceded by @auth.login_required, which is actually the secret of the

# There are @auth.login_required signs to call this method, pass token or pass the account number and password
@auth. Verify_password
def verify_password (username_or_ token, password):
  # First Verify token
  user = User.verify_auth_token (username_or_token)
  if not user:
    # Then verify the username and password user
    = User.query.filter_by (username=username_or_token). I if not,
    or not User.verify_ Password (password): return
      False
  g.user = user return
  True

Finally write an entry method

if __name__ = = ' __main__ ':
  # If the database does not exist, create if not
  os.path.exists (' Db.sqlite '):
    db.create_all ()
  App.run (Debug=true)

That's it.

Effect chart

Registered

Login

Verifying token

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.