How to serve Flask With Http Server
我想开发一个同时使用Flask和httpd的应用程序。
Flask发布与HTML相关的文件,而httpd发布本地文件中的文件。
它用于浏览Flask HTML中以httpd发布的本地文件。
尽管Flask和httpd的端口号不同,但似乎httpd服务器端无法正常工作。
连接到httpd服务器时发生连接拒绝错误。
添加了问题的意图。
我想通过脚本同时运行Flask的内置Web服务器和HTTPServer。
我只希望能够看到自己,而不是将其暴露给网络。
我正在寻找一种无需使用WSGI即可通过app.py脚本完成的机制。
向该问题添加了其他信息。
这个问题使用Flask和Python的HTTPServer,但是使用NodeJS的HTTPServer而不是HTTPServer似乎效果很好。
(注释
如果可能,我想在Python中完成而不使用NodeJS HTTPServer。
https://www.npmjs.com/package/http-server
1 2 3 4 5 6 | C:\Users\User\Videos>http-server Starting up http-server, serving ./ Available on: http://127.0.0.1:8080 Hit CTRL-C to stop the server ... |
版
1 2 | Flask==1.0.2 Python 3.7 |
我不能使用以下代码启动每个服务器吗?
templates / index.html
1 2 3 4 5 6 7 8 9 10 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <video src="http://localhost:8080/video.mp4"></video> </body> </html> |
python(app.py)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | from http.server import SimpleHTTPRequestHandler, HTTPServer from flask import Flask, render_template app = Flask(__name__) @app.route('/') def hello_world(): return render_template('index.html') class Handler(SimpleHTTPRequestHandler): def __init__(self, *args, directory=None, **kwargs): super().__init__(*args, directory=r'C:\Users\User\Videos', **kwargs) def run(server_class=HTTPServer, handler_class=Handler): server_address = ('localhost', 8000) httpd = server_class(server_address, handler_class) httpd.serve_forever() if __name__ == '__main__': app.run(host='localhost', port=5000) run() |
它可能传输不佳。对不起。
非常感谢你。
Can I not start each server with the following code?
是的,还有许多其他方法。
WSGI
PEP 333中定义了
This document specifies a proposed standard interface between web
servers and Python web applications or frameworks, to promote web
application portability across a variety of web servers.
框架方面
Web服务器端
有很多选择,您可以在wsgi.org上找到更多选择:
- 古尼康
- uWSGI
- ...
基本上,您可以选择任何一种来启动服务器,并使用
mod_wsgi is an Apache module that embeds a Python application within
the server and allow them to communicate through the Python WSGI
interface as defined in the Python PEP 333.
注意
对于更新的问题
I want to run Flask's built-in web server and HTTPServer
simultaneously from a script.
只需运行Shell命令
您可以启动另一个进程并使用Popen调用shell命令:
1 2 3 | if __name__ == '__main__': p = Popen(['python -m http.server'], shell=True) app.run(host='localhost', port=5000) |
使用您喜欢的任何命令,甚至可以在此处启动节点http服务器。
使用线程/进程
您可以在另一个线程或进程中启动http服务器,这里以线程为例:
1 2 3 4 | if __name__ == '__main__': from threading import Thread Thread(target=run, daemon=True).start() app.run(host='localhost', port=5000) |
使用烧瓶服务文件
您实际上可以使用
1 2 3 4 | @app.route('/videos/<path:filename>') def download_file(filename): return send_from_directory(r'C:\Users\User\Videos', filename, as_attachment=True) |
您可以查看文档以了解更多详细信息。
app.run()是一项阻止操作。以下几行将不予解释。
从单独的文件或在不同的线程/进程中运行您的应用程序。