flask前后台交互數據的幾個思路


通過url進行參數傳遞:

@app.route('/hello/<name>')   # <name>為傳遞的參數  
def hello(name=None):           
    return render_template('src/hello.html',name=name) 

hello.html的內容:

<!doctype html>  
<title>Hello from Flask</title>  
{% if name %}  
<h1>Hello {{ name }}!</h1>  
{% else %}  
<h1>Hello World!</h1>  
{% endif %}  

其 中,name作為傳入的變量。render_template()方法可以用來直接渲染模板,免去繁瑣的html生成工作。 render_template方法只需傳入需要渲染的模板名和傳遞個模板引擎(flask采用的是Jinja2)的參數。模板名需要放置在項目根目錄下 的templates目錄。

HTTP方法:

flask中一個route默認只應答http的get方法。可以通過methods參數指定具體能夠應答的http方法。

@app.route('/test', methods=['POST','GET'])    # 可以應答POST和GET方法  
def test():  
    print(request.method)                      # request對象封裝了http的request請求  
    print(request.form['username'])            # form為前端的表單,request.form屬於dict類型  
    return 'response back'                     # 返回字符串類型的結果  

如果要返回json字符串,可以使用如下方法:

jsonStr={'result':'hello world'}  
return jsonify(jsonStr)                        # 或者json.dumps(jsonStr)

jsonStr 是dict類型,然后通過jsonify方法直接將dict類型轉換為json串。當然也可以使用json.dumps(jsonStr)將dict轉換 為json字符串。jsonify是flask自帶的json處理類,返回的為flask結果,處理json串還攜帶了content- type="application/json"。json.dumps是單純的轉換為json串。另外json.dumps能夠處理的類型比 jsonify多,比如list類型。

靜態文件:

靜態文件(比如css等)需要存放於根目錄下的static目錄下。可以通過url_for方法產生靜態文件的url。 比如:

url_for('static', filename='style.css')

cookies&session:

讀取cookie參數:

from flask import request  
@app.route('/')  
def index():  
    username = request.cookies.get('username')  
    # use cookies.get(key) instead of cookies[key] to not get a  
    # KeyError if the cookie is missing. 

設置cookie參數:

from flask import make_response  
@app.route('/')  
def index():  
    resp = make_response(render_template(...))    # Converts the return value from a view function to a real response object that is an instance of response_class.  
    resp.set_cookie('username', 'the username')  
    return resp 

session的一個例子:

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'])    # session是dict類型  
    return 'You are not logged in'  
@app.route('/login', methods=['GET', 'POST'])  
def login():  
    if request.method == 'POST':  
        session['username'] = request.form['username']            # 設置session中的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)                                 # 移除session中的username變量  
    return redirect(url_for('index'))  
# set the secret key.  keep this really secret:  
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

密鑰的獲取方式:

>>> import os  
>>> os.urandom(24) 

通過ajax讀寫后台數據


通過json讀寫數據


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM