欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

Flask之flask-script 指定端口

发布时间:2023/11/30 45 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Flask之flask-script 指定端口 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

简介

Flask-Scropt插件为在Flask里编写额外的脚本提供了支持。这包括运行一个开发服务器,一个定制的Python命令行,用于执行初始化数据库、定时任务和其他属于web应用之外的命令行任务的脚本。

安装

用命令pip和easy_install安装:

pip install Flask-Script

从github下载最新版本,源码编译安装:

git clone https://github.com/smurfix/flask-script.git cd flask-script python setup.py develop

创建并运行命令行

第一步:实例化manage对象

需要创建一个可以运行你脚本命令的Python模块。你可以随意命名它。我这里就以manage.py为例。

 在manage.py文件中,需要先创建一个Manager实例。Manager类会跟踪所有的命令和命令行调用的参数:

from flask_script import Managerapp = Flask(__name__) # configure your appmanager = Manager(app)if __name__ == "__main__":manager.run()

调用manager.run()方法初始化Mnager实例来接收命令行输入。

此时,已经可以通过命令启动项目了,如下:

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的,只是本质也是127.0.0.1

第二步:创建添加自定义命令

创建自定义命令有三种方法:

  • 定义Command类的子类
  • 使用@command装饰器
  • 使用@option装饰器

(1) 定义Command类的子类

为了简单,我们就创建一个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()的参数: manager.run({'hello' : Hello()})

(2)使用@command装饰器

 对于简单的命令,我们可以使用属于Manager实例的@command装饰器。

@manager.command def hello():"Just say hello"print("hello")

其使用方法和前面一样。

 (3)使用@option装饰器

如何需要通过命令行进行比较复杂的控制,可以使用Manager实例的@option装饰器。

@manager.option('-n', '--name', help='Your name') def hello(name):print("hello", name)

使用

python manage.py -n '付勇'

  则会输出:‘hello 付勇’

转载于:https://www.cnblogs.com/jiangchunsheng/p/9218340.html

总结

以上是生活随笔为你收集整理的Flask之flask-script 指定端口的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。