Flask 【第二篇】Flask基礎
知識點回顧
1、flask依賴wsgi,實現wsgi的模塊:wsgiref,werkzeug,uwsgi
2、實例化Flask對象,裏面是有參數的
app = Flask(__name__,template_folder=‘templates‘,static_url_path=‘/xxxxxx‘)
3、兩種添加路由的方式
方式一: @app.route(‘/xxxx‘) # @decorator def index(): return "Index" 方式二: def index(): return "Index" app.add_url_rule(‘/xxx‘, "n1", index) #n1是別名
4、添加路由關系的本質
將url和視圖函數封裝成一個Rule對象)添加到Flask的url_map字段中
5、Flask中裝飾器應用
from flask import Flask,render_template,request,redirect,session app = Flask(__name__) app.secret_key = "sdsfdsgdfgdfgfh" def wrapper(func): def inner(*args,**kwargs): if not session.get("user_info"): return redirect("/login") ret = func(*args,**kwargs) return ret return inner @app.route("/login",methods=["GET","POST"]) def login(): if request.method=="GET": return render_template("login.html") else: # print(request.values) #這個裏面什麽都有,相當於body username = request.form.get("username") password = request.form.get("password") if username=="haiyan" and password=="123": session["user_info"] = username # session.pop("user_info") #刪除session return redirect("/index") else: # return render_template("login.html",**{"msg":"用戶名或密碼錯誤"}) return render_template("login.html",msg="用戶名或者密碼錯誤") @app.route("/index",methods=["GET","POST"]) @wrapper def index(): # if not session.get("user_info"): # return redirect("/login") return render_template("index.html") if __name__ == ‘__main__‘: app.run(debug=True)
5、請求響應相關
- request - request.form #POST請求 - request.args #GET請求 字典形式的 - request.querystring #GET請求,bytes形式的 - response - return render_tempalte() - return redirect() - return "" v = make_response(返回值) #吧返回的值包在了這個函數裏面 - session - 存在瀏覽器上,並且是加密的 - 依賴於:secret_key
flask配置文件
flask中的配置文件是一個flask.config.Config對象(繼承字典),默認配置為: { ‘DEBUG‘: get_debug_flag(default=False), 是否開啟Debug模式 ‘TESTING‘: False, 是否開啟測試模式 ‘PROPAGATE_EXCEPTIONS‘: None, ‘PRESERVE_CONTEXT_ON_EXCEPTION‘: None, ‘SECRET_KEY‘: None, ‘PERMANENT_SESSION_LIFETIME‘: timedelta(days=31), ‘USE_X_SENDFILE‘: False, ‘LOGGER_NAME‘: None, ‘LOGGER_HANDLER_POLICY‘: ‘always‘, ‘SERVER_NAME‘: None, ‘APPLICATION_ROOT‘: None, ‘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, ‘MAX_CONTENT_LENGTH‘: None, ‘SEND_FILE_MAX_AGE_DEFAULT‘: timedelta(hours=12), ‘TRAP_BAD_REQUEST_ERRORS‘: False, ‘TRAP_HTTP_EXCEPTIONS‘: False, ‘EXPLAIN_TEMPLATE_LOADING‘: False, ‘PREFERRED_URL_SCHEME‘: ‘http‘, ‘JSON_AS_ASCII‘: True, ‘JSON_SORT_KEYS‘: True, ‘JSONIFY_PRETTYPRINT_REGULAR‘: True, ‘JSONIFY_MIMETYPE‘: ‘application/json‘, ‘TEMPLATES_AUTO_RELOAD‘: None, } 方式一: app.config[‘DEBUG‘] = True PS: 由於Config對象本質上是字典,所以還可以使用app.config.update(...) 方式二: app.config.from_pyfile("python文件名稱") 如: settings.py DEBUG = True app.config.from_pyfile("settings.py") app.config.from_envvar("環境變量名稱") 環境變量的值為python文件名稱名稱,內部調用from_pyfile方法 app.config.from_json("json文件名稱") JSON文件名稱,必須是json格式,因為內部會執行json.loads app.config.from_mapping({‘DEBUG‘:True}) 字典格式 app.config.from_object("python類或類的路徑") app.config.from_object(‘pro_flask.settings.TestingConfig‘) settings.py class Config(object): DEBUG = False TESTING = False DATABASE_URI = ‘sqlite://:memory:‘ class ProductionConfig(Config): DATABASE_URI = ‘mysql://user@localhost/foo‘ class DevelopmentConfig(Config): DEBUG = True class TestingConfig(Config): TESTING = True PS: 從sys.path中已經存在路徑開始寫 PS: settings.py文件默認路徑要放在程序root_path目錄,如果instance_relative_config為True,則就是instance_path目錄
一、路由系統
1、可傳入參數:
@app.route(‘/user/<username>‘) #常用的 不加參數的時候默認是字符串形式的 @app.route(‘/post/<int:post_id>‘) #常用的 #指定int,說明是整型的 @app.route(‘/post/<float:post_id>‘) @app.route(‘/post/<path:path>‘) @app.route(‘/login‘, methods=[‘GET‘, ‘POST‘])
常用路由系統有以上五種,所有的路由系統都是基於一下對應關系來處理:
DEFAULT_CONVERTERS = { ‘default‘: UnicodeConverter, ‘string‘: UnicodeConverter, ‘any‘: AnyConverter, ‘path‘: PathConverter, ‘int‘: IntegerConverter, ‘float‘: FloatConverter, ‘uuid‘: UUIDConverter, }
2、反向生成URL: url_for
endpoint("name") #別名,相當於django中的name
反向解析需要導入:
from flask import Flask, url_for
@app.route(‘/index‘,endpoint="xxx") #endpoint是別名 def index(): v = url_for("xxx") print(v) return "index" @app.route(‘/zzz/<int:nid>‘,endpoint="aaa") #endpoint是別名 def zzz(nid): v = url_for("aaa",nid=nid) print(v) return "index2"
3、@app.route和app.add_url_rule參數
@app.route和app.add_url_rule參數: rule, URL規則 view_func, 視圖函數名稱 defaults=None, 默認值,當URL中無參數,函數需要參數時,使用defaults={‘k‘:‘v‘}為函數提供參數 endpoint=None, 名稱,用於反向生成URL,即: url_for(‘名稱‘) methods=None, 允許的請求方式,如:["GET","POST"] strict_slashes=None, 對URL最後的 / 符號是否嚴格要求, 如: @app.route(‘/index‘,strict_slashes=False), 訪問 http://www.xx.com/index/ 或 http://www.xx.com/index均可 @app.route(‘/index‘,strict_slashes=True) 僅訪問 http://www.xx.com/index redirect_to=None, 重定向到指定地址 如: @app.route(‘/index/<int:nid>‘, redirect_to=‘/home/<nid>‘) 或 def func(adapter, nid): return "/home/888" @app.route(‘/index/<int:nid>‘, redirect_to=func)
subdomain=None, 子域名訪問 from flask import Flask, views, url_for app = Flask(import_name=__name__) app.config[‘SERVER_NAME‘] = ‘haiyan.com:5000‘ @app.route("/", subdomain="admin") def static_index(): """Flask supports static subdomains This is available at static.your-domain.tld""" return "admin.xxx.com" #動態生成 @app.route("/dynamic", subdomain="<username>") def username_index(username): """Dynamic subdomains are also supported Try going to user1.your-domain.tld/dynamic""" return username + ".your-domain.tld" if __name__ == ‘__main__‘: app.run() 所有的域名都得與IP做一個域名解析:
如果你想通過域名去訪問,有兩種解決方式:
方式一:
1、租一個域名 haiyan.lalala
2、租一個公網IP 49.8.5.62
3、域名解析:
haiyan.com 49.8.5.62
4、吧代碼放在49.8.5.62這個服務器上,程序運行起來
用戶可以通過IP進行訪問
方式二:如果是自己測試用的就可以用這種方式。先在自己本地的文件中找
C:\Windows\System32\drivers\etc 找到HOST,修改配置
然後吧域名修改成自己的本地服務器127.0.0.1
加上配置:app.config["SERVER_NAME"] = "haiyan.com:5000"
練習以上的參數
redirect_to:直接重定向,原url有參數時,跳轉是也得傳參,註意:不用加類型
#/old @app.route(‘/old/<int:nid>‘,redirect_to="/new/<nid>") def old(nid): return "old" # /new @app.route(‘/new/<int:nid>‘) def new(nid): return "new"
# ============對url最後的/符號是否嚴格要求========= @app.route(‘/test‘,strict_slashes=True) #當為True時,url後面必須不加斜杠 def test(): return "aaaaaaaa" @app.route(‘/test‘,strict_slashes=False) #當為False時,url上加不加斜杠都行 def test(): return "aaaaaaaa"
# =============== 子域名訪問============ @app.route("/static_index", subdomain="admin") def static_index(): return "admin.bjg.com" # ===========動態生成子域名=========== @app.route("/index",subdomain=‘<xxxxx>‘) def index(xxxxx): return "%s.bjg.com" %(xxxxx,)
擴展Flask的路由系統,讓他支持正則,這個類必須這樣寫,必須去繼承BaseConverter
from flask import Flask,url_for app = Flask(__name__) # 定義轉換的類 from werkzeug.routing import BaseConverter class RegexConverter(BaseConverter): """ 自定義URL匹配正則表達式 """ def __init__(self, map, regex): super(RegexConverter, self).__init__(map) self.regex = regex def to_python(self, value): """ 路由匹配時,匹配成功後傳遞給視圖函數中參數的值 :param value: :return: """ return int(value) def to_url(self, value): """ 使用url_for反向生成URL時,傳遞的參數經過該方法處理,返回的值用於生成URL中的參數 :param value: :return: """ val = super(RegexConverter, self).to_url(value) return val # 添加到converts中 app.url_map.converters[‘regex‘] = RegexConverter # 進行使用 @app.route(‘/index/<regex("\d+"):nid>‘,endpoint=‘xx‘) def index(nid): url_for(‘xx‘,nid=123) #反向生成,就會去執行to_url方法 return "Index" if __name__ == ‘__main__‘: app.run()
二、視圖函數
1、diango中的CBV模式
2、Flask中的CBV模式
def auth(func): def inner(*args, **kwargs): result = func(*args, **kwargs) return result return inner class IndexView(views.MethodView): # methods = [‘POST‘] #只允許POST請求訪問 decorators = [auth,] #如果想給所有的get,post請求加裝飾器,就可以這樣來寫,也可以單個指定 def get(self): #如果是get請求需要執行的代碼 v = url_for(‘index‘) print(v) return "GET" def post(self): #如果是post請求執行的代碼 return "POST"
app.add_url_rule(‘/index‘, view_func=IndexView.as_view(name=‘index‘)) #name指定的是別名,會當做endpoint使用 if __name__ == ‘__main__‘: app.run()
3、Flask中的FBV模式
兩種方式:
方式一: @app.route(‘/index‘,endpoint=‘xx‘) def index(nid): url_for(‘xx‘,nid=123) return "Index" 方式二: def index(nid): url_for(‘xx‘,nid=123) return "Index" app.add_url_rule(‘/index‘,index)
三、請求與響應
from flask import Flask from flask import request from flask import render_template from flask import redirect from flask import make_response app = Flask(__name__) @app.route(‘/login.html‘, methods=[‘GET‘, "POST"]) def login(): # 請求相關信息 # request.method # request.args # request.form # request.values # request.cookies # request.headers # request.path # request.full_path # request.script_root # request.url # request.base_url # request.url_root # request.host_url # request.host # request.files # obj = request.files[‘the_file_name‘] # obj.save(‘/var/www/uploads/‘ + secure_filename(f.filename)) # 響應相關信息 # return "字符串" # return render_template(‘html模板路徑‘,**{}) # return redirect(‘/index.html‘) # response = make_response(render_template(‘index.html‘)) # response是flask.wrappers.Response類型 # response.delete_cookie(‘key‘) # response.set_cookie(‘key‘, ‘value‘) # response.headers[‘X-Something‘] = ‘A value‘ # return response return "內容" if __name__ == ‘__main__‘: app.run()
from flask import Flask,url_for,request,redirect,render_template,jsonify,make_response from urllib.parse import urlencode,quote,unquote app = Flask(__name__) @app.route(‘/index‘,endpoint=‘xx‘) def index(): from werkzeug.datastructures import ImmutableMultiDict
================= # get_data = request.args # get_dict = get_data.to_dict() # get_dict[‘xx‘] = ‘18‘ # url = urlencode(get_dict) # print(url) ==================== # print(request.query_string) # print(request.args) ========================== # val = "%E6%8A%8A%E5%87%A0%E4%B8%AA" # print(unquote(val)) #吧上面這樣的數據轉換成中文 # # return "Index" # return "Index" # return redirect() # return render_template() # return jsonify(name=‘alex‘,age=‘18‘) #相當於JsonResponse ======================= response = make_response(‘xxxxx‘) ##如果是返回更多的值,cookie,headers,或者其他的就可用它 response.headers[‘xxx‘] = ‘123123‘ return response if __name__ == ‘__main__‘: # app.__call__ app.run()
四、模板語法
1、為了防止xss攻擊,加了驗證,所以頁面上顯示字符串的形式,解決辦法,有兩種方式
- 在後端Markup
v5 = Markup("<input type=‘text‘ />")
- 在前端
{{ v4|safe }}
2、自定義方法
def test(a,b): return a+b @app.route(‘/index‘) def index(): return render_template("index2.html",test=test) index2.html <h1>{{ test(1,2) }}</h1>
3、寫一個函數在所有的頁面都使用
template_global和template_filter
@app.template_global() def sb(a1, a2): return a1 + a2 @app.template_filter() def db(a1, a2, a3): return a1 + a2 + a3
調用方式:{{sb(1,2)}} {{ 1|db(2,3)}}
4、模板繼承:和django的一樣。extents
5、宏:只有定義的東西在很多地方去使用的時候才去用它
{% macro input(name, type=‘text‘, value=‘‘) %} <input type="{{ type }}" name="{{ name }}" value="{{ value }}"> {% endmacro %} {{ input(‘n1‘) }}
練習:
模板語法from flask import Flask,url_for,render_template,Markup app = Flask(__name__) def test(a,b): return a+b @app.template_global() def sb(a1, a2): return a1 + a2 + 100 @app.template_filter() def db(a1, a2, a3): return a1 + a2 + a3 @app.route(‘/index‘) def index(): v1 = "字符串" v2 = [11,22,33] v3 = {"k1":"v3","sdf":"sdgfgf"} v4 = "<input type=‘text‘ />" v5 = Markup("<input type=‘text‘ />") return render_template("index2.html",v1=v1,v2=v2,v3=v3,v4=v4,v5=v5,test=test) if __name__ == ‘__main__‘: app.run(debug=True)
index2.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width"> <title>Title</title> </head> <body> {{ v1 }} <ul> {% for foo in v2 %} <li>{{ foo }}</li> {% endfor %} {{ v2.1 }} {% for k,v in v3.items() %} <li>{{ k }} {{ v }}</li> {% endfor %} {{ v3.k1 }} {{ v3.get("k1") }} {{ v4|safe }} {{ v5 }} <h1>{{ test(1,2) }}</h1> <p>{{ sb(1,2) }}</p> <p>{{ 1| db(2,3) }}</p> </ul> </body> </html>
五、session
除請求對象之外,還有一個 session 對象。它允許你在不同請求間存儲特定用戶的信息。它是在 Cookies 的基礎上實現的,並且對 Cookies 進行密鑰簽名要使用會話,你需要設置一個密鑰。
-
設置:session[‘username‘] = ‘xxx‘
- 刪除:session.pop(‘username‘, None)
from flask import Flask,url_for,session app = Flask(__name__) app.secret_key = "sdsfdgdgdgd" app.config[‘SESSION_COOKIE_NAME‘] = ‘session_lvning‘ #設置session的名字 @app.route(‘/index/‘) def index(nid): #session本質上操作的是字典, session是否還有其他方法?與字典方法相同 #session的原理:如果下一次訪問的時候帶著隨機字符串,會把session裏面對應的 # 值拿到內存,假設session保存在數據庫,每執行一次鏈接一次數據庫,每次都要時時更新的話 # 會非常損耗內存 session["xxx"] = 123 session["xxx2"] = 123 session["xxx3"] = 123 session["xxx4"] = 123 del session["xxx2"] #在這刪除了,真正存儲的時候是沒有xxx2的 return "ddsf" if __name__ == ‘__main__‘: app.run()
關於session的配置
app.config[‘SESSION_COOKIE_NAME‘] = ‘session_lvning‘
- session超時時間如何設置? ‘PERMANENT_SESSION_LIFETIME‘: timedelta(days=31)
以下是跟session相關的配置文件
""" ‘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)基本使用
from flask import Flask, session, redirect, url_for, escape, request app = Flask(__name__) @app.route(‘/‘) def index(): if ‘username‘ in session: return ‘Logged in as %s‘ % escape(session[‘username‘]) return ‘You are not logged in‘ @app.route(‘/login‘, methods=[‘GET‘, ‘POST‘]) def login(): if request.method == ‘POST‘: session[‘username‘] = request.form[‘username‘] return redirect(url_for(‘index‘)) return ‘‘‘ <form action="" method="post"> <p><input type=text name=username> <p><input type=submit value=Login> </form> ‘‘‘ @app.route(‘/logout‘) def logout(): # remove the username from the session if it‘s there session.pop(‘username‘, None) return redirect(url_for(‘index‘)) # set the secret key. keep this really secret: app.secret_key = ‘A0Zr98j/3yX R~XHH!jmN]LWX/,?RT‘
自定義Session
pip3 install Flask-Session run.py from flask import Flask from flask import session from pro_flask.utils.session import MySessionInterface app = Flask(__name__) app.secret_key = ‘A0Zr98j/3yX R~XHH!jmN]LWX/,?RT‘ app.session_interface = MySessionInterface() @app.route(‘/login.html‘, methods=[‘GET‘, "POST"]) def login(): print(session) session[‘user1‘] = ‘alex‘ session[‘user2‘] = ‘alex‘ del session[‘user2‘] return "內容" if __name__ == ‘__main__‘: app.run() session.py #!/usr/bin/env python # -*- coding:utf-8 -*- import uuid import json from flask.sessions import SessionInterface from flask.sessions import SessionMixin from itsdangerous import Signer, BadSignature, want_bytes class MySession(dict, SessionMixin): def __init__(self, initial=None, sid=None): self.sid = sid self.initial = initial super(MySession, self).__init__(initial or ()) def __setitem__(self, key, value): super(MySession, self).__setitem__(key, value) def __getitem__(self, item): return super(MySession, self).__getitem__(item) def __delitem__(self, key): super(MySession, self).__delitem__(key) class MySessionInterface(SessionInterface): session_class = MySession container = {} def __init__(self): import redis self.redis = redis.Redis() def _generate_sid(self): return str(uuid.uuid4()) def _get_signer(self, app): if not app.secret_key: return None return Signer(app.secret_key, salt=‘flask-session‘, key_derivation=‘hmac‘) def open_session(self, app, request): """ 程序剛啟動時執行,需要返回一個session對象 """ sid = request.cookies.get(app.session_cookie_name) if not sid: sid = self._generate_sid() return self.session_class(sid=sid) signer = self._get_signer(app) try: sid_as_bytes = signer.unsign(sid) sid = sid_as_bytes.decode() except BadSignature: sid = self._generate_sid() return self.session_class(sid=sid) # session保存在redis中 # val = self.redis.get(sid) # session保存在內存中 val = self.container.get(sid) if val is not None: try: data = json.loads(val) return self.session_class(data, sid=sid) except: return self.session_class(sid=sid) return self.session_class(sid=sid) def save_session(self, app, session, response): """ 程序結束前執行,可以保存session中所有的值 如: 保存到resit 寫入到用戶cookie """ domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) val = json.dumps(dict(session)) # session保存在redis中 # self.redis.setex(name=session.sid, value=val, time=app.permanent_session_lifetime) # session保存在內存中 self.container.setdefault(session.sid, val) session_id = self._get_signer(app).sign(want_bytes(session.sid)) response.set_cookie(app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure)
第三方session
#!/usr/bin/env python # -*- coding:utf-8 -*- """ pip3 install redis pip3 install flask-session """ from flask import Flask, session, redirect from flask.ext.session import Session app = Flask(__name__) app.debug = True app.secret_key = ‘asdfasdfasd‘ app.config[‘SESSION_TYPE‘] = ‘redis‘ from redis import Redis app.config[‘SESSION_REDIS‘] = Redis(host=‘192.168.0.94‘,port=‘6379‘) Session(app) @app.route(‘/login‘) def login(): session[‘username‘] = ‘alex‘ return redirect(‘/index‘) @app.route(‘/index‘) def index(): name = session[‘username‘] return name if __name__ == ‘__main__‘: app.run()
六、blueprint,藍圖
詳情見第三章
七、閃現 : flash
session存在在服務端的一個字典裏面,session保存起來,取一次裏面還是有的,直到你刪除之後才沒有了
1、本質:flash是基於session創建的,flash支持往裏邊放值,只要你取一下就沒有了,相當於pop了一下。不僅吧值取走,而且吧session裏的東西去掉
2、閃現有什麽用?
from flask import Flask,session,Session,flash,get_flashed_messages,redirect,render_template,request app = Flask(__name__) app.secret_key =‘sdfsdfsdf‘ @app.route(‘/users‘) def users(): # 方式一 # msg = request.args.get(‘msg‘,‘‘) # 方式二 # msg = session.get(‘msg‘) # if msg: # del session[‘msg‘] # 方式三 v = get_flashed_messages() print(v) msg = ‘‘ return render_template(‘users.html‘,msg=msg) @app.route(‘/useradd‘) def user_add(): # 在數據庫中添加一條數據 # 假設添加成功,在跳轉到列表頁面時,顯示添加成功 # 方式一 # return redirect(‘/users?msg=添加成功‘) # 方式二 # session[‘msg‘] = ‘添加成功‘ # 方式三 flash(‘添加成功‘) return redirect(‘/users‘) if __name__ == ‘__main__‘: app.run(debug=True)
八、擴展
1、在函數執行之前或函數執行之後做點事情
第一種:裝飾器
第二種:flask裏面的擴展,相當於django中的中間件
from flask import Flask,session,Session,flash,get_flashed_messages,redirect,render_template,request app = Flask(__name__) app.secret_key =‘sdfsdfsdf‘ @app.before_request def process_request1(): print(‘process_request1‘) @app.after_request def process_response1(response): print(‘process_response1‘) return response @app.before_request def process_request2(): print(‘process_request2‘) @app.after_request def process_response2(response): #參數也得有 print(‘process_response2‘) return response #必須有返回值 @app.route(‘/index‘) def index(): print(‘index‘) return ‘Index‘ @app.route(‘/order‘) def order(): print(‘order‘) return ‘order‘ @app.route(‘/test‘) def test(): print(‘test‘) return ‘test‘ if __name__ == ‘__main__‘: app.run()
運行結果:
還有一個@app.before_first_request:表示,當程序運行起來,第一個請求來的時候就只執行一次,下次再來就不會在執行了
Flask 【第二篇】Flask基礎