安装Flask
- pip install Flask
- pip install -r requirements.txt
下面是flask的启动
- flask run
- flask run --host 0.0.0.0
- flask run --help
-
- #windows下
- set FLASK_APP=index_1.py
- #Linux下
- export FLASK_APP=index_1.py
优化程序,不要这么多命令就能运行。直接python运行
- if __name__ == "__main__":
- app.run(host = "0.0.0.0", debug = True)
如下面这个Hello World程序:
- from flask import Flask
-
- app = Flask(__name__)
-
- @app.route("/")
- def hello():
- return "Hello World"
-
- if __name__ == "__main__":
- app.run(host = "0.0.0.0", debug = True)
运行截图如下:
Flask为什么可以独立运行
在Flask源码中可以看到
这里的Werkzeug:WSGI工具包,作为web框架底层库。
当用户发起请求时:web browser -> web server -> WSGI server
服务器回数据:WSGI server -> web server -> web browser
如下简单的程序
- class Shortly(object):
- def __call__(self, environ, start_response):
- start_response("https://cdn.jxasp.com:9143/image/200 ok", [("content-Type", "text / plain")]);
- return [b"HelloWord"]
-
- if __name__ == "__main__":
- from werkzeug.serving import run_simple
- app = Shortly()
- run_simple("0.0.0.0", 5001, app)
程序运行截图如下:
另外一个例子:
- from werkzeug.wrappers import Request, Response
-
- class Shortly(object):
- def __call__(self, environ, start_response):
- request = Request(environ)
- text = "hello World"
- response = Response(text, mimetype = "text/plain")
- return response(environ, start_response)
-
- if __name__ == "__main__":
- from werkzeug.serving import run_simple
- app = Shortly()
- run_simple("0.0.0.0", 5001, app)
如果要传参数:
- from werkzeug.wrappers import Request, Response
-
- class Shortly(object):
- def __call__(self, environ, start_response):
- request = Request(environ)
- text = "hello World %s" % (request.args.get("a", "IT1995"))
- response = Response(text, mimetype = "text/plain")
- return response(environ, start_response)
-
- if __name__ == "__main__":
- from werkzeug.serving import run_simple
- app = Shortly()
- run_simple("0.0.0.0", 5001, app)
程序运行截图如下:
下面是项目中常用的启动方式:
使用变量的方式启动DEBUG
- from flask import Flask
-
- app = Flask(__name__)
- app.config["DEBUG"] = True
-
- @app.route("/")
- def hello():
- return "Hello World"
-
- if __name__ == "__main__":
- app.run(host = "0.0.0.0")
使用文件
一般都用这种
- from flask import Flask
-
- app = Flask(__name__)
- app.config.from_pyfile("config/base_setting.py")
-
- @app.route("/")
- def hello():
- return "Hello World"
-
- if __name__ == "__main__":
- app.run(host = "0.0.0.0")
这里新建的config目录下的base_setting.py
DEBUG = True