簡介:
Flask基于python開發并依賴于jinjia2和werkzeug WSGI服務一個微型框架.
Werkzeug本質是Socket服務端,用來接收http請求并對請求進行預處理,然后觸發Flask框架,
開發人員基于Flask框架提供的功能對請求進行相應的處理,并回傳給用戶,如果要回傳給用戶復雜內容時,
需要借助jinjia2模板來實作對模板的處理,即:將模板和資料進行渲染,江選然后的字串回傳給用戶.
我們用python直接寫Web業務,剩下的TCP連接,HTTP原始請求和回應格式就需要一個統一的介面協議來實作,
這個介面就是WSGI(Web Server Gateway Interface),wsgiref就是python基于wsgi協議開發的服務模塊.代碼如下:
from wsgiref.simple_server import make_server def mya(environ, start_response): print(environ) start_response('200 OK', [('Content-Type', 'text/html')]) if environ.get('PATH_INFO') == '/index': with open('index.html','rb') as f: data=f.read() elif environ.get('PATH_INFO') == '/login': with open('login.html', 'rb') as f: data = f.read() else: data=b'<h1>Hello, web!</h1>' return [data] if __name__ == '__main__': myserver = make_server('', 8011, mya) print('監聽8010') myserver.serve_forever() wsgiref簡單應用 我們平時寫flask的代碼其實就是在改寫mya這個函式的內容
1.安裝Flask:
pip install flask
2.Werkzeug
Werkzeug是WSGI的一個工具包,可以作為Web框架的底層庫.(因為Werkzeug里面封裝了好多web框架的東西,入Request,Response等)
代碼:
from werkzeug.wrappers import Request, Response @Request.application def hello(request): return Response('Hello World!') if __name__ == '__main__': from werkzeug.serving import run_simple run_simple('localhost', 4000, hello)
3.flask簡單使用
from flask import Flask # 實體化產生一個Flask物件 app = Flask(__name__) # 將 '/'和視圖函式hello_workd的對應關系添加到路由中,flask所有的路由都是在裝飾其中添加的 @app.route('/') # 1. v=app.route('/') 2. v(hello_world) def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run() # 最終呼叫了run_simple()
例子:登錄,顯示用戶資訊
主檔案(xxx.py):
from flask import Flask,render_template,request,redirect,session,url_for app = Flask(__name__) app.debug = True app.secret_key = 'sdfsdfsdfsdf' USERS = { 1:{'name':'張三','age':18,'gender':'男','text':"道路千萬條"}, 2:{'name':'李四','age':28,'gender':'男','text':"安全第一條"}, 3:{'name':'王五','age':18,'gender':'女','text':"行車不規范"}, } @app.route('/detail/<int:nid>',methods=['GET']) def detail(nid): user = session.get('user_info') if not user: return redirect('/login') info = USERS.get(nid) return render_template('detail.html',info=info) @app.route('/index',methods=['GET']) def index(): user = session.get('user_info') if not user: # return redirect('/login') url = url_for('l1') return redirect(url) return render_template('index.html',user_dict=USERS) @app.route('/login',methods=['GET','POST'],endpoint='l1') def login(): if request.method == "GET": return render_template('login.html') else: # request.query_string user = request.form.get('user') pwd = request.form.get('pwd') if user == 'cxw' and pwd == '123': session['user_info'] = user return redirect('http://www.baidu.com') return render_template('login.html',error='用戶名或密碼錯誤') if __name__ == '__main__': app.run()
前端:
三種前端取值方式:
①dic.name
②dic['name']
③dic.get('name')
html檔案:
detail.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>詳細資訊 {{info.name}}</h1> <div> {{info.text}} </div> </body> </html>
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>詳細資訊 {{info.name}}</h1> <div> {{info.text}} </div> </body> </html>
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>用戶登錄</h1> <form method="post"> <input type="text" name="user"> <input type="text" name="pwd"> <input type="submit" value="登錄">{{error}} </form> </body> </html>
4.flask的組態檔:
{ '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 app.debug=True 也行 PS: 由于Config物件本質上是字典,所以還可以使用app.config.update(...)
法二:
#通過py檔案配置 app.config.from_pyfile("python檔案名稱") 如: settings.py DEBUG = True app.config.from_pyfile("settings.py") #通過環境變數配置 app.config.from_envvar("環境變數名稱") #app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS']) 環境變數的值為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目錄(Flask物件init方法的引數)
5.flask路由
標準語法: @app.route('/detail/<int:nid>',methods=['GET'],endpoint='detail')
默認轉換器
DEFAULT_CONVERTERS = { 'default': UnicodeConverter, 'string': UnicodeConverter, 'any': AnyConverter, 'path': PathConverter, 'int': IntegerConverter, 'float': FloatConverter, 'uuid': UUIDConverter, }
路由系統本質:
""" 1. decorator = app.route('/',methods=['GET','POST'],endpoint='n1') def route(self, rule, **options): # app物件 # rule= / # options = {methods=['GET','POST'],endpoint='n1'} def decorator(f): endpoint = options.pop('endpoint', None) self.add_url_rule(rule, endpoint, f, **options) return f return decorator 2. @decorator decorator(index) """ #同理 def login(): return '登錄' app.add_url_rule('/login', 'n2', login, methods=['GET',"POST"]) #與django路由類似 #django與flask路由:flask路由基于裝飾器,本質是基于:add_url_rule #add_url_rule 原始碼中,endpoint如果為空,endpoint = _endpoint_from_view_func(view_func),最終取view_func.__name__(函式名)
6.模板
渲染變數: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>用戶串列</h1> <table> {% for k,v in user_dict.items() %} <tr> <td>{{k}}</td> <td>{{v.name}}</td> <td>{{v['name']}}</td> <td>{{v.get('name')}}</td> <td><a href=https://www.cnblogs.com/shengjunqiye/p/"/detail/{{k}}">查看詳細</a></td> </tr> {% endfor %} </table> </body> </html> 變數回圈: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>用戶串列</h1> <table> {% for k,v in user_dict.items() %} <tr> <td>{{k}}</td> <td>{{v.name}}</td> <td>{{v['name']}}</td> <td>{{v.get('name')}}</td> <td><a href=https://www.cnblogs.com/shengjunqiye/p/"/detail/{{k}}">查看詳細</a></td> </tr> {% endfor %} </table> </body> </html> 邏輯判斷: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>用戶串列</h1> <table> {% if name %} <h1>Hello {{ name }}!</h1> {% else %} <h1>Hello World!</h1> {% endif %} </table> </body> </html>
傳參:直接在return后面的口號內直接加逗號,直接寫引數即可
主檔案: from flask import Flask,render_template,Markup,jsonify,make_response app = Flask(__name__) def func1(arg): return Markup("<input type='text' value='https://www.cnblogs.com/shengjunqiye/p/%s' />" %(arg,)) #Markup和django的make_safe一樣 @app.route('/') def index(): return render_template('index.html',ff = func1)#引數func1就傳過去了 if __name__ == '__main__': app.run() html檔案中: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {{ff('六五')}} #使用ff變數 {{ff('六五')|safe}} </body> </html>
extends,include和django一樣
7.請求回應:
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 get請求提及的資料 # request.form post請求提交的資料 # request.values post和get提交的資料總和 # request.cookies 客戶端所帶的cookie # request.headers 請求頭 # request.path 不帶域名,請求路徑 # request.full_path 不帶域名,帶引數的請求路徑 # request.script_root # request.url 帶域名帶引數的請求路徑 # request.base_url 帶域名請求路徑 # request.url_root 域名 # request.host_url 域名 # request.host 127.0.0.1:500 # 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') #return jsonify({'k1':'v1'}) # 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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/152955.html
標籤:Python
上一篇:Python爬蟲-有道翻譯
