86. Some messy and 86flask knowledge points
Navigate to this article:
- Session component
- Context and built-in functions
- Pymysql Problems
- Template Problems
I. session Components
1. session component Introduction
Flask-session is the session component of the flask framework. Because the original flask built-in session is saved using the signature cookie, this component stores the session in multiple places, for example:
- Redis: A Tool for saving data, five main types. Non-relational databases
- Memcached
- Filesystem
- Mongodb
- Sqlalchmey: store the data in the database table.
Install
pip3 install flask-session
2. Storage Mode
#! /Usr/bin/env python #-*-coding: UTF-8-import redisfrom flask import Flask, sessionfrom flask_session import Sessionapp = Flask (_ name _) app. debug = Trueapp. secret_key = 'xxxx' app. config ['session _ type'] = 'redis '# The session type is redisapp. config ['session _ PERMANENT '] = False # if it is set to True, closing the browser SESSION becomes invalid. App. config ['session _ USE_SIGNER '] = False # Whether to encrypt the cookie value sent to the SESSION on the browser. config ['session _ key_prefix'] = 'session: '# prefix of the value saved to the SESSION app. config ['session _ REDIS '] = redis. redis (host = '2017. 0.0.1 ', port = '000000', password = '000000') # used to connect to the redis configuration Session (app) @ app. route ('/Index') def index (): session ['k1 '] = 'v1 'Return 'xx' if _ name _ =' _ main _ ': app. run ()
Redis
#! /Usr/bin/env python #-*-coding: UTF-8-import redisfrom flask import Flask, sessionfrom flask_session import Sessionimport memcacheapp = Flask (_ name _) app. debug = Trueapp. secret_key = 'xxxx' app. config ['session _ type'] = 'memcached' # The session type is redisapp. config ['session _ PERMANENT '] = True # if it is set to True, closing the browser SESSION becomes invalid. App. config ['session _ USE_SIGNER '] = False # Whether to encrypt the cookie value sent to the SESSION on the browser. config ['session _ key_prefix'] = 'session: '# prefix of the value saved to the SESSION app. config ['session _ MEMCACHED '] = memcache. client (['10. 211.55.4: 12000 ']) Session (app) @ app. route ('/Index') def index (): session ['k1 '] = 'v1 'Return 'xx' if _ name _ =' _ main _ ': app. run ()
Memcached
#! /Usr/bin/env python #-*-coding: UTF-8-import redisfrom flask import Flask, sessionfrom flask_session import Sessionapp = Flask (_ name _) app. debug = Trueapp. secret_key = 'xxxx' app. config ['session _ type'] = 'filesystem' # The session type is redisapp. config ['session _ FILE_DIR '] ='/Users/wupeiqi/PycharmProjects/grocery/96. new Flask Course/component/2. flask-session '# The session type is redisapp. config ['session _ FILE_THRESHOLD '] = 500 # If the number of stored sessions is greater than this value, the app will be deleted. config ['session _ FILE_MODE '] = 384 # File Permission type app. config ['session _ PERMANENT '] = True # if it is set to True, closing the browser SESSION becomes invalid. App. config ['session _ USE_SIGNER '] = False # Whether to encrypt the cookie value sent to the SESSION on the browser. config ['session _ key_prefix'] = 'session: '# prefix of the value saved to the SESSION session (app) @ app. route ('/Index') def index (): session ['k1 '] = 'v1 'session ['k2'] = 'v1 'Return 'xx' if _ name _ =' _ main __': app. run ()
Filesystem
#! /Usr/bin/env python #-*-coding: UTF-8-import redisfrom flask import Flask, sessionfrom flask_session import Sessionimport py1_app = Flask (_ name _) app. debug = Trueapp. secret_key = 'xxxx' app. config ['session _ type'] = 'mongodb '# The session type is redisapp. config ['session _ MONGODB '] = pymongo. consumer Client () app. config ['session _ MONGODB_DB '] = 'database name of mongo (Database Name)' app. config ['session _ MONGODB_COLLECT '] = 'mongo c Ollect name (Table Name) 'app. config ['session _ PERMANENT '] = True # if it is set to True, closing the browser SESSION becomes invalid. App. config ['session _ USE_SIGNER '] = False # Whether to encrypt the cookie value sent to the SESSION on the browser. config ['session _ key_prefix'] = 'session: '# prefix of the value saved to the SESSION session (app) @ app. route ('/Index') def index (): session ['k1 '] = 'v1 'session ['k2'] = 'v1 'Return 'xx' if _ name _ =' _ main __': app. run ()
Mongodb
#! /Usr/bin/env python #-*-coding: UTF-8-*-from pymongo import Export Client # create link conn = export client ('47. 93.4.198 ', 27017) # select database db = conn ['db1'] # select table posts = db ['posts'] post_data = {'name': 'Alex ', 'age': 18} # insert data in the table # result = posts. insert_one (post_data) # Get a piece of data # row = posts. find_one () # print (row) # obtain multiple data records # rows = posts. find () # for row in rows: # print (row) # Delete multiple data entries # rows = posts. delete_rows (filter ={}) # print (rows) # update multiple data records # posts. update ({},{ 'name': 'wupeiqi '})
Simple mongodb operation example
#! /Usr/bin/env python #-*-coding: UTF-8-import redisfrom flask import Flask, sessionfrom flask_session import Session as FSessionfrom flask_sqlalchemy import SQLAlchemyapp = Flask (_ name __) app. debug = Trueapp. secret_key = 'xxxx' # Set the database link app. config ['sqlalchemy _ DATABASE_URI '] = 'mysql + pymysql: // root: 123@127.0.0.1: 3306/fssa? Charset = utf8' app. config ['sqlalchemy _ TRACK_MODIFICATIONS '] = True # instantiate SQLAlchemydb = SQLALCHEMY (app) app. config ['session _ type'] = 'sqlalchemy '# The session type is sqlalchemyapp. config ['session _ SQLALCHEMY '] = db # SQLAlchemy object app. config ['session _ SQLALCHEMY_TABLE '] = 'session' # Name of the table to be saved in the SESSION app. config ['session _ PERMANENT '] = True # if it is set to True, closing the browser SESSION becomes invalid. App. config ['session _ USE_SIGNER '] = False # Whether to encrypt the cookie value sent to the SESSION on the browser. config ['session _ key_prefix'] = 'session: '# prefix of the value saved to the SESSION FSession (app) @ app. route ('/Index') def index (): session ['k1 '] = 'v1 'session ['k2'] = 'v1 'Return 'xx' if _ name _ =' _ main __': app. run ()
Sqlalchemy
PS: After writing the code, do not worry about running it. You need to run the following command on the terminal to create a database table:
bogon:pro-flask wupeiqi$ python3Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44)[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> from app import db>>> db.create_all()>>>
3. Application scenarios
If the application is small, use native encryption ccokie to save the session (built-in)
From flask import Flask, sessionapp = Flask (_ name _) app. secret_key = 'sdfsdfsdf 'app. config ['session _ COOKIE_NAME '] = 'session _ lvning' "" 'session _ COOKIE_NAME ': 'session', 'session _ COOKIE_DOMAIN ': None, 'session _ COOKIE_PATH ': None, 'session _ COOKIE_HTTPONLY': True, 'session _ COOKIE_SECURE ': False, 'session _ REFRESH_EACH_REQUEST': True, 'permanent _ SESSION_LIFETIME ': timedelta (days = 31) "" @ app. route ('/Index', endpoint = 'xx') def index (): # session essentially operates on dictionaries, suppose the session is stored in the database # session ['xxx'] = 123 # session ['xx1'] = 123 # session ['xx2 '] = 123 # session ['xx3'] = 123 # del session ['xx2 '] session ['xx3'] = 123 return "xxx" if _ name _ =' _ main __': # app. _ call _ app. run ()
View Code
If the application is large, use redis (flask-session)
Ii. Context and built-in functions
1. Context
Class Sxw (object): def _ enter _ (self): ''' enter ''' print ("hello") def _ exit _ (self, exc_type, exc_val, exc_tb): ''' exit ''' print ("hao") obj = Sxw () with obj: print ("in progress ")
Print results
2. built-in functions
Object. xxx generally executes _ setattr __,__ getattr _ object ["xx"] and generally executes _ setitem __,__ getitem _ with open as f: usually run the _ enter __,__ exit _ with context usage. When opening a file, you may forget to close the file. In this way, the file is automatically closed.
Iii. pymysql Problems
1. The result returned by pymysql is a tuples. to print the result in a dictionary, add a parameter.
2. When passing parameters, do not pass the default parameter to a variable data type.
Iv. template Problems
1. Two static file import methods
1) method 1
2) method 2
2. The template syntax in flask is not prompted. solution:
Click to select jinja2