Python 在后台启动 Flask 服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24941791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:29:44  来源:igfitidea点击:

Starting flask server in background

pythonpython-2.7flaskcelery

提问by Uday

I have a flask application which I am currently starting up in the following way:

我有一个烧瓶应用程序,我目前正在通过以下方式启动:

#phantom.py
__author__ = 'uruddarraju'
from phantom.api.v1 import app
app.run(host='0.0.0.0', port=8080, debug=True)

and when I run this script, it executes successfully by printing:

当我运行这个脚本时,它通过打印成功执行:

loading config from /home/uruddarraju/virtualenvs/PHANTOMNEW/Phantom/etc/phantom/phantom.ini
* Running on http://0.0.0.0:8080/

But it never returns and if I do a CTRL-C the server stops. I am trying to deploy this to production and want to run this startup on the background, where the process stays up as long as the server is up.

但它永远不会返回,如果我执行 CTRL-C,服务器就会停止。我正在尝试将其部署到生产中,并希望在后台运行此启动程序,只要服务器启动,进程就会保持运行状态。

What is the best way to do this?

做这个的最好方式是什么?

采纳答案by RaphDG

My favorite way of doing it in production is to combine flask with uwsgi and nginx to keep persistence. Here are nice setup instructions to get you started: http://www.markjberger.com/flask-with-virtualenv-uwsgi-nginx/

我最喜欢在生产中这样做的方式是将烧瓶与 uwsgi 和 nginx 结合起来以保持持久性。这里有很好的设置说明,可以帮助您入门:http: //www.markjberger.com/flask-with-virtualenv-uwsgi-nginx/

Jist:

吉斯特:

First make sure that your vps has the latest updates:

首先确保您的 vps 具有最新更新:

sudo apt-get update
sudo apt-get upgrade

Now install python and virtualenv:

现在安装 python 和 virtualenv:

sudo apt-get install build-essential python-dev python-pip
sudo pip install virtualenv

Make a folder for your website:

为您的网站创建一个文件夹:

sudo mkdir -p /var/www/mysite
sudo chown -R <your user id> /var/www/mysite
cd /var/www/mysite

Setup virtualenv and install flask:

设置 virtualenv 并安装 Flask:

virtualenv .env --no-site-packages
source .env/bin/activate
pip install flask

Place your flask app in this folder. Make sure that your host is set to 0.0.0.0 and that your app is under if __name__ == '__main__':. If your app is in a function, uwsgi will not be able to call it.

将您的烧瓶应用程序放在此文件夹中。确保您的主机设置为 0.0.0.0 并且您的应用程序在 if 下__name__ == '__main__':。如果您的应用程序在函数中,uwsgi 将无法调用它。

Now is a good time to test your app with the flask development server to see if everything is working so far. If everything runs smoothly, install nginx and uwsgi:

现在是使用 Flask 开发服务器测试您的应用程序以查看到目前为止一切是否正常的好时机。如果一切顺利,安装 nginx 和 uwsgi:

deactivate
sudo apt-get install nginx uwsgi uwsgi-plugin-python

Next we must create a socket file for nginx to communicate with uwsgi:

接下来我们必须为nginx创建一个socket文件来与uwsgi通信:

cd /tmp/
touch mysite.sock
sudo chown www-data mysite.sock

By changing the owner of mysite.sock to www-data, nginx will be able to write to the socket. Now all we have to do is add our configuration files for nginx and uwsgi. First delete the default configuration for nginx:

通过将 mysite.sock 的所有者更改为 www-data,nginx 将能够写入套接字。现在我们要做的就是为 nginx 和 uwsgi 添加我们的配置文件。首先删除nginx的默认配置:

cd /etc/nginx/sites-available
sudo rm default

Create a new configuration file mysite and add the following:

创建一个新的配置文件 mysite 并添加以下内容:

server {
    listen 80;
    server_tokens off;
    server_name www.mysite.com mysite.com;

     location / {
         include uwsgi_params;
         uwsgi_pass unix:/tmp/mysite.sock;
     }

     location /static {
         alias /var/www/mysite/static;
     }

     ## Only requests to our Host are allowed
     if ($host !~ ^(mysite.com|www.mysite.com)$ ) {
        return 444;
     }
}

In order to enable the site, we must link our configuration file to /etc/nginx/sites-enabled/:

为了启用站点,我们必须将我们的配置文件链接到 /etc/nginx/sites-enabled/:

sudo ln -s /etc/nginx/sites-available/mysite /etc/nginx/sites-enabled/mysite

The process is similar for uwsgi. Create the file /etc/uwsgi/apps-available/mysite.ini and add the following:

uwsgi 的过程类似。创建文件 /etc/uwsgi/apps-available/mysite.ini 并添加以下内容:

[uwsgi]
vhost = true
socket = /tmp/mysite.sock
venv = /var/www/mysite/.env
chdir = /var/www/mysite
module = app
callable = app

Module is the name of your python script and callable is the name of your flask instance. So if your flask site was in a file called mysite.py that looked like this:

Module 是 Python 脚本的名称, callable 是 Fl​​ask 实例的名称。因此,如果您的烧瓶站点位于名为 mysite.py 的文件中,如下所示:

from flask import Flask
my_app = Flask(__name__)

@my_app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    my_app.run(host='0.0.0.0')

Your mysite.ini file would be:

您的 mysite.ini 文件将是:

module = mysite
callable = my_app

Link the configuration file to the enabled-apps folder:

将配置文件链接到 enabled-apps 文件夹:

sudo ln -s /etc/uwsgi/apps-available/mysite.ini /etc/uwsgi/apps-enabled/mysite.ini

Finally, restart nginx and uwsgi:

最后重启nginx和uwsgi:

sudo service nginx restart
sudo service uwsgi restart

回答by Joran Beasley

$ python phantom.py &

Is probably the easiest way to make it run in the background. That said you should not be using the app.run() server to serve your flask app if you are moving it into production as @LukasGraf mentions (as well as I believe their documentation)

可能是让它在后台运行的最简单方法。也就是说,如果您像@LukasGraf 提到的那样将其投入生产(以及我相信他们的文档),则不应使用 app.run() 服务器来为您的烧瓶应用程序提供服务

回答by allo

Try Supervisord. It starts commands as a specified user and restarts them after they terminate. The config is very simple for what you want to do.

尝试Supervisord。它以指定用户的身份启动命令,并在它们终止后重新启动它们。对于您想要做的事情,配置非常简单。

回答by Bizzu

Probably the best way to do this is behind nginx like @RaphDG answered, But if you want to run it in the background for personal use I found that the logging system would not let you to use only with "&" at the end of the command line, in addition i found that the logger is internal logger of Werkzeug library.

可能最好的方法是在 nginx 后面,就像@RaphDG 回答的那样,但是如果你想在后台运行它供个人使用,我发现日志系统不会让你只在结尾处使用“&”命令行,此外我发现记录器是 Werkzeug 库的内部记录器。

To get around this you can do the next steps(code below):

要解决此问题,您可以执行以下步骤(下面的代码):

  1. import werkzeug._internal
  2. create demi logger class
  3. Assign the new class to werkzeug._internal._log (log class)
  1. 导入werkzeug._internal
  2. 创建半记录器类
  3. 将新类分配给 werkzeug._internal._log(日志类)

It will evade notifications and loggers and let you run this process in the background (with "&")

它将逃避通知和记录器,并让您在后台运行此进程(使用“&”)

code:

代码:

import werkzeug._internal

def demi_logger(type, message,*args,**kwargs):
    pass

the first line in the __main__:

__main__ 中的第一行:

werkzeug._internal._log = demi_logger