Create a simple login System Using Python and log on to python
This time I will mainly explain how to use Python Flask-based login and registration, and Basic Auth for verification.
Mainly used for the next Database
Import OS # Flask basic library from flask import Flask, abort, request, jsonify, g, url_for # Flaks database operation library from flask. ext. sqlalchemy import SQLAlchemy # Flask log on to the registered library from flask. ext. httpauth import HTTPBasicAuth # from passlib. apps import custom_app_context as pwd_context # URL Security serialization tool from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired)
First of all, it is initialization.
App = Flask (_ name _) # Set the secret app. config ['secret _ key'] = 'the quick brown fox jumps over the lazy dog' # configure the database app. config ['sqlalchemy _ DATABASE_URI '] = 'sqlite: // db. sqlite 'app. config ['sqlalchemy _ commit_on_tearlow'] = True # Database initialization db = SQLALCHEMY (app) # verified initialization auth = HTTPBasicAuth ()
ThenModeling
SQLAlchemy Is An ORM model that operates databases, so it is very convenient.
Besides basic attributes, we have defined some necessary methods.
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 (64) # encrypted password def hash_password (self, password): self. password_hash = pwd_context.encrypt (password) # verify the password def verify_password (self, password): return pwd_context.verify (password, self. password_hash) # generate the token and set the 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 token verification method @ staticmethod def verify_auth_token (token): s = Serializer (app. config ['secret _ key']) try: data = s. loads (token) expires t SignatureExpired: return None # token expired expires t BadSignature: return None # token invalid user = User. query. get (data ['id']) return user
RegisterFunction
@ 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) # empty username or password if User. query. filter_by (username = username ). first () is not None: abort (400) # The user already exists User = user (username = username) # encrypt the password user. hash_password (password) # Save it to the database. session. add (user) db. session. commit () # return the user name after successful registration, followed by the jump address return (jsonify ({'username': user. username}), 201, {'location': url_for ('get _ user', id = user. id, _ external = True )})
LoginFunction
# Get the token@app.route after logging on ('/api/token') @ auth. login_requireddef get_auth_token (): # Set token expiration time token = g. user. generate_auth_token (600) return jsonify ({'Token': token. decode ('ascii '), 'duration': 600 })
After obtaining the token, you only need to pass the token for each request.
We can verify whether the token is valid using one method.
# You can use the token or account password to log on to @ app. route ('/api/resource') @ auth. login_requireddef get_resource (): # If the token is valid, return username return jsonify ({'data': 'Hello, % s! '% G. user. username })
Careful people will find that the above two methods have @ auth. login_required, which is actually the secret
# @ Auth. this method must be called for all login_required flag, and the token or account and password @ auth must be passed. verify_passworddef verify_password (username_or_token, password): # verify the token user = User first. verify_auth_token (username_or_token) if not user: # verify the user name and password. query. filter_by (username = username_or_token ). first () if not user 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)
This is all done.
Register
Login
Verify token
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.