Flask快速搭建簡單服務器
Flask真是一個強大且簡介的web框架,可以快速搭建web服務器,簡單,高效。
近期需要做一個本地服務器,用來接收量化平臺傳回來的交易信號,然後調用對應的交易API,以及交易信號的存儲。
考慮到只是簡單的接收信號和少量數據存儲,而且沒有高併發的要求,所以實用sqlite3作爲後端存儲。
下面記錄下簡單的Flask發送和接收http請求和參數解析。
項目名稱是:autotrade
1.Flaskf服務器
# autotrade/__init__.py
# __init__.py 定義全局的app路由
# 然後將其他模塊由app裝飾後的函數導入,flask即可識別所有的請求入口
from flask import Flask
from multiprocessing import Process
# 配置全局app
app = Flask(__name__)
# 導入index中定義的所有函數
from autotrade.server.index import *
def run_index():
# 啓動web服務器,使用多線程方式,接收所有http請求
app.run(host='0.0.0.0', port=5000, threaded=True)
def run_orders():
# 啓動查詢交易程序
while True:
print('執行相應的交易程序')
time.sleep(3)
def main():
# 主程序
# 創建子進程
jobs = []
jobs.append(Process(target=run_index))
jobs.append(Process(target=run_orders))
# 啓動子進程
for job in jobs:
job.start()
# 等待子進程結束返回
for job in jobs:
job.join()
if __name__ == '__main__':
main()
2.http請求接口
# autotrade/server/index.py
# 在這裏寫對應的http接口函數
import datetime
from flask import Flask, request
# 引用路由
from autotrade.server import app
@app.route('/')
def index():
"""index.html主頁返回"""
return 'I have receive you request !'
@app.route('/order', methods=['GET', 'POST', 'DELETE'])
def order():
"""/order.html接口,接收get請求,解析url中的參數"""
print(request.url) # 請求的http網址
data = request.args.to_dict() # 解析http中的參數
# to something here
return str(data) # 注意,不管什麼問題,一定要返回,就算是返回None
然後我們執行 autotrade/__init__.py
啓動flask服務器,在瀏覽器中輸入網址 localhost:5000
或者 localhost:5000/sync
,觀察python的輸出以及瀏覽器的返回結果,查看服務器是否正常啓動。
3.request請求
使用request的GET或者POST方法,實現數據回傳。
import requests
data = {'id':123, 'name':'XiaoMing'} # 請求的參數,或者說是要傳輸的數據
url='http://localhost:5000/sync' # 請求的flask地址
r=requests.get(url,params=data) # 獲取服務器響應
print(r.status_code) # 打印狀態,200表示正常返回
print(r.text) # 打印返回結果
至此,用Flask搭建簡單的服務器就完成了,實現是簡答的數據回傳功能,是不是很簡單啊。當然,flask可以實現很複雜的網站設計,因爲知乎就是用flask開發的。