日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

Python-基于flask的接口框架

發(fā)布時(shí)間:2025/3/21 python 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python-基于flask的接口框架 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Python-基于flask的接口框架

?Flask是一個(gè)Python編寫的Web 微框架,讓我們可以使用Python語言快速實(shí)現(xiàn)一個(gè)網(wǎng)站或Web服務(wù)。本文參考自Flask官方文檔,大部分代碼引用自官方文檔。

安裝flask

首先我們來安裝Flask。最簡(jiǎn)單的辦法就是使用pip。

pip install flask

然后打開一個(gè)Python文件,輸入下面的內(nèi)容并運(yùn)行該文件。然后訪問localhost:5000,我們應(yīng)當(dāng)可以看到瀏覽器上輸出了hello world。

from flask import Flaskapp = Flask(__name__)?@app.route('/')def hello_world(): return 'hello world'?if __name__ == '__main__': app.run(host='127.0.0.1',port=5000)

調(diào)試模式

我們修改代碼中的輸出,然后查看瀏覽器上是否有變化。如果你照做的話,可以看到什么變化都沒有。其實(shí)Flask內(nèi)置了調(diào)試模式,可以自動(dòng)重載代碼并顯示調(diào)試信息。這需要我們開啟調(diào)試模式,方法很簡(jiǎn)單,設(shè)置FLASK_DEBUG環(huán)境變量,并將值設(shè)置為1。或者設(shè)置app.debug=True

?

from flask import Flask?app = Flask(__name__)app.debug=True?@app.route('/')def hello_world(): return 'Hello World!'?@app.route('/login')def login(): return 'Login'??if __name__ == '__main__': app.run()

?

然后再次運(yùn)行程序,會(huì)看到有這樣的輸出。這時(shí)候如果再次修改代碼,會(huì)發(fā)現(xiàn)這次Flask會(huì)自動(dòng)重啟。

* Restarting with stat
* Debugger is active!
* Debugger PIN: 157-063-180
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

路由

在上面的例子里可以看到路由的使用。如果了解Spring Web MVC的話,應(yīng)該對(duì)路由很熟悉。路由通過使用Flask的app.route裝飾器來設(shè)置,這類似Java的注解。

@app.route('/')def index(): return 'Index Page'?@app.route('/hello')def hello(): return 'Hello, World'

?

路徑變量

如果希望獲取/article/1這樣的路徑參數(shù),就需要使用路徑變量。路徑變量的語法是/path/<converter:varname>。在路徑變量前還可以使用可選的轉(zhuǎn)換器,有以下幾種轉(zhuǎn)換器。

轉(zhuǎn)換器作用
string默認(rèn)選項(xiàng),接受除了斜杠之外的字符串
int接受整數(shù)
float接受浮點(diǎn)數(shù)
path和string類似,不過可以接受帶斜杠的字符串
any匹配任何一種轉(zhuǎn)換器
uuid接受UUID字符串

下面是Flask官方的例子。

?

@app.route('/user/<username>')def show_user_profile(username): # show the user profile for that user return 'User %s' % username?@app.route('/post/<int:post_id>')def show_post(post_id): # show the post with the given id, the id is an integer return 'Post %d' % post_id

?

構(gòu)造URL

在Web程序中常常需要獲取某個(gè)頁面的URL,在Flask中需要使用url_for('方法名')來構(gòu)造對(duì)應(yīng)方法的URL。下面是Flask官方的例子。

>>> from flask import Flask, url_for>>> app = Flask(__name__)>>> @app.route('/')... def index(): pass...>>> @app.route('/login')... def login(): pass...>>> @app.route('/user/<username>')... def profile(username): pass...>>> with app.test_request_context():... print url_for('index')... print url_for('login')... print url_for('login', next='/')... print url_for('profile', username='John Doe')...//login/login?next=//user/John%20Doe

HTTP方法

如果需要處理具體的HTTP方法,在Flask中也很容易,使用route裝飾器的methods參數(shù)設(shè)置即可。

?

from flask import request?@app.route('/login', methods=['GET', 'POST'])def login(): if request.method == 'POST': do_the_login() else: show_the_login_form()

日志輸出

Flask 為我們預(yù)配置了一個(gè) Logger,我們可以直接在程序中使用。這個(gè)Logger是一個(gè)標(biāo)準(zhǔn)的Python Logger,所以我們可以向標(biāo)準(zhǔn)Logger那樣配置它,詳情可以參考官方文檔。

app.logger.debug('A value for debugging')app.logger.warning('A warning occurred (%d apples)', 42)app.logger.error('An error occurred')

?

處理請(qǐng)求

在 Flask 中獲取請(qǐng)求參數(shù)需要使用request等幾個(gè)全局對(duì)象,但是這幾個(gè)全局對(duì)象比較特殊,它們是?Context Locals?,其實(shí)就是 Web 上下文中局部變量的代理。雖然我們?cè)诔绦蛑惺褂玫氖侨肿兞?#xff0c;但是對(duì)于每個(gè)請(qǐng)求作用域,它們都是互不相同的變量。理解了這一點(diǎn),后面就非常簡(jiǎn)單了。

?

Request 對(duì)象

Request 對(duì)象是一個(gè)全局對(duì)象,利用它的屬性和方法,我們可以方便的獲取從頁面?zhèn)鬟f過來的參數(shù)。

method屬性會(huì)返回HTTP方法的類似,例如post和get。form屬性是一個(gè)字典,如果數(shù)據(jù)是POST類型的表單,就可以從form屬性中獲取。下面是 Flask 官方的例子,演示了 Request 對(duì)象的method和form屬性。

?

from flask import request?@app.route('/login', methods=['POST', 'GET'])def login(): error = None if request.method == 'POST': if valid_login(request.form['username'], request.form['password']): return log_the_user_in(request.form['username']) else: error = 'Invalid username/password' # the code below is executed if the request method # was GET or the credentials were invalid return render_template('login.html', error=error)

?

如果數(shù)據(jù)是由GET方法傳送過來的,可以使用args屬性獲取,這個(gè)屬性也是一個(gè)字典。

searchword = request.args.get('key', '')

?

文件上傳

利用Flask也可以方便的獲取表單中上傳的文件,只需要利用 request 的files屬性即可,這也是一個(gè)字典,包含了被上傳的文件。如果想獲取上傳的文件名,可以使用filename屬性,不過需要注意這個(gè)屬性可以被客戶端更改,所以并不可靠。更好的辦法是利用werkzeug提供的secure_filename方法來獲取安全的文件名。

?

from flask import requestfrom werkzeug.utils import secure_filename?@app.route('/upload', methods=['GET', 'POST'])def upload_file(): if request.method == 'POST': f = request.files['the_file'] f.save('/var/www/uploads/' + secure_filename(f.filename))

寫在最后

這篇文章主要參考了Flask的官方文檔,但是只介紹了 Flask的最基本的一部分。了解了這部分,我們可以用Python 搭一個(gè)小服務(wù)器做點(diǎn)事情。如果希望詳細(xì)了解 Flask的使用用法,請(qǐng)關(guān)注更詳細(xì)的資料。

?

?

?

總結(jié)

以上是生活随笔為你收集整理的Python-基于flask的接口框架的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。