Flask之flask-script 指定端口
簡介
Flask-Scropt插件為在Flask里編寫額外的腳本提供了支持。這包括運行一個開發(fā)服務(wù)器,一個定制的Python命令行,用于執(zhí)行初始化數(shù)據(jù)庫、定時任務(wù)和其他屬于web應(yīng)用之外的命令行任務(wù)的腳本。
安裝
用命令pip和easy_install安裝:
pip install Flask-Script從github下載最新版本,源碼編譯安裝:
git clone https://github.com/smurfix/flask-script.git cd flask-script python setup.py develop創(chuàng)建并運行命令行
第一步:實例化manage對象
需要創(chuàng)建一個可以運行你腳本命令的Python模塊。你可以隨意命名它。我這里就以manage.py為例。
?在manage.py文件中,需要先創(chuàng)建一個Manager實例。Manager類會跟蹤所有的命令和命令行調(diào)用的參數(shù):
from flask_script import Managerapp = Flask(__name__) # configure your appmanager = Manager(app)if __name__ == "__main__":manager.run()調(diào)用manager.run()方法初始化Mnager實例來接收命令行輸入。
此時,已經(jīng)可以通過命令啟動項目了,如下:
python manage.py runserver項目會以:Running on http://127.0.0.1:5000/ 的方式啟動,
如需指定ip和端口:
python manage.py runserver -h 127.0.0.1 -p 8090項目則會以:Running on http://127.0.0.1:8090/ 的方式啟動,其實也是可以指定IP的,只是本質(zhì)也是127.0.0.1
第二步:創(chuàng)建添加自定義命令
創(chuàng)建自定義命令有三種方法:
- 定義Command類的子類
- 使用@command裝飾器
- 使用@option裝飾器
(1) 定義Command類的子類
為了簡單,我們就創(chuàng)建一個hello命令來輸出“hello world”:
from flask_script import Commandclass Hello(Command):"prints hello world"def run(self):print "hello world"接下來我們需要把命令添加到Mannager實例:
manager.add_command('hello', Hello())完整代碼如下:
from flask_script import Manager,Command from flask import Flask app = Flask(__name__)manager = Manager(app)class hello(Command):"prints hello world"def run(self):print("hello world")manager.add_command('hello', hello())if __name__ == "__main__":manager.run()?使用:
在命令行運行如下命令: (1)$python manage.py hello hello world (2)$python manage.py usage: manage.py [-?] {hello,shell,runserver} ...positional arguments:{hello,shell,runserver}hello prints hello worldshell Runs a Python shell inside Flask application context.runserver Runs the Flask development server i.e. app.run()optional arguments:-?, --help show this help message and exit也可以通過把包含Command實例的字典作為manager.run()的參數(shù): manager.run({'hello' : Hello()})(2)使用@command裝飾器
?對于簡單的命令,我們可以使用屬于Manager實例的@command裝飾器。
@manager.command def hello():"Just say hello"print("hello")其使用方法和前面一樣。
?(3)使用@option裝飾器
如何需要通過命令行進行比較復(fù)雜的控制,可以使用Manager實例的@option裝飾器。
@manager.option('-n', '--name', help='Your name') def hello(name):print("hello", name)使用
python manage.py -n '付勇'則會輸出:‘hello 付勇’
轉(zhuǎn)載于:https://www.cnblogs.com/jiangchunsheng/p/9218340.html
總結(jié)
以上是生活随笔為你收集整理的Flask之flask-script 指定端口的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pyhive 连接 Hive 时错误
- 下一篇: 做男性不育检需到新乡哪家医院好