Python-基于flask的接口框架
Python-基于flask的接口框架
?Flask是一個Python編寫的Web 微框架,讓我們可以使用Python語言快速實現(xiàn)一個網(wǎng)站或Web服務。本文參考自Flask官方文檔,大部分代碼引用自官方文檔。
安裝flask
首先我們來安裝Flask。最簡單的辦法就是使用pip。
pip install flask然后打開一個Python文件,輸入下面的內(nèi)容并運行該文件。然后訪問localhost:5000,我們應當可以看到瀏覽器上輸出了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)試模式
我們修改代碼中的輸出,然后查看瀏覽器上是否有變化。如果你照做的話,可以看到什么變化都沒有。其實Flask內(nèi)置了調(diào)試模式,可以自動重載代碼并顯示調(diào)試信息。這需要我們開啟調(diào)試模式,方法很簡單,設置FLASK_DEBUG環(huán)境變量,并將值設置為1。或者設置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()?
然后再次運行程序,會看到有這樣的輸出。這時候如果再次修改代碼,會發(fā)現(xiàn)這次Flask會自動重啟。
* 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的話,應該對路由很熟悉。路由通過使用Flask的app.route裝飾器來設置,這類似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)換器。
| string | 默認選項,接受除了斜杠之外的字符串 |
| int | 接受整數(shù) |
| float | 接受浮點數(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程序中常常需要獲取某個頁面的URL,在Flask中需要使用url_for('方法名')來構(gòu)造對應方法的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%20DoeHTTP方法
如果需要處理具體的HTTP方法,在Flask中也很容易,使用route裝飾器的methods參數(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 為我們預配置了一個 Logger,我們可以直接在程序中使用。這個Logger是一個標準的Python Logger,所以我們可以向標準Logger那樣配置它,詳情可以參考官方文檔。
app.logger.debug('A value for debugging')app.logger.warning('A warning occurred (%d apples)', 42)app.logger.error('An error occurred')?
處理請求
在 Flask 中獲取請求參數(shù)需要使用request等幾個全局對象,但是這幾個全局對象比較特殊,它們是?Context Locals?,其實就是 Web 上下文中局部變量的代理。雖然我們在程序中使用的是全局變量,但是對于每個請求作用域,它們都是互不相同的變量。理解了這一點,后面就非常簡單了。
?
Request 對象
Request 對象是一個全局對象,利用它的屬性和方法,我們可以方便的獲取從頁面?zhèn)鬟f過來的參數(shù)。
method屬性會返回HTTP方法的類似,例如post和get。form屬性是一個字典,如果數(shù)據(jù)是POST類型的表單,就可以從form屬性中獲取。下面是 Flask 官方的例子,演示了 Request 對象的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屬性獲取,這個屬性也是一個字典。
searchword = request.args.get('key', '')?
文件上傳
利用Flask也可以方便的獲取表單中上傳的文件,只需要利用 request 的files屬性即可,這也是一個字典,包含了被上傳的文件。如果想獲取上傳的文件名,可以使用filename屬性,不過需要注意這個屬性可以被客戶端更改,所以并不可靠。更好的辦法是利用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 搭一個小服務器做點事情。如果希望詳細了解 Flask的使用用法,請關(guān)注更詳細的資料。
?
?
?
總結(jié)
以上是生活随笔為你收集整理的Python-基于flask的接口框架的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【新星计划】 Python的txt文本操
- 下一篇: 【新星计划】Python print输出