近日将一些代码放在服务器上运行,遂用Flask+Python3+Apache2.4+Ubuntu组合来进行配置。具体如下。

Flask(Python)
若使用虚拟环境,可在预设的 Web 目录下使用如下命令建立虚拟环境,并激活。
python3 -m venv venvname
source venvname/bin/activate
然后安装程序运行所需要的 Python 包(如 flask 等)。
pip install flask
# pip install -r requirements.txt
在与主程序同目录下建立 wsgi 文件(如 flask.wsgi),写入以下内容。
import sys
activate = "Your_Web_Root/venvname/bin/activate_this.py"
def execfile(filename):
globals = dict(__file__=filename)
exec(open(filename).read(), globals)
execfile(activate)
sys.path.insert(0, "Your_Web_Root")
from YourApp import app
application = app
如果不使用 venv,可用下面的代码。
import sys
sys.path.insert(0, 'Your_Web_Root')
from YourApp import app as application
如果 venvname/bin/ 目录下没有 activate_this.py,可以新建一个,内容如下(若不适用 venv,可不用创建本文件)。
"""By using execfile(this_file, dict(__file__=this_file)) you will
activate this virtualenv environment.
This can be used when you must use an existing Python interpreter, not
the virtualenv bin/python
"""
try:
__file__
except NameError:
raise AssertionError(
"You must run this like execfile('path/to/activate_this.py', dict(__file__='path/to/activate_this.py'))")
import sys
import os
old_os_path = os.environ['PATH']
os.environ['PATH'] = os.path.dirname(os.path.abspath(__file__)) + os.pathsep + old_os_path
base = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if sys.platform == 'win32':
site_packages = os.path.join(base, 'Lib', 'site-packages')
else:
site_packages = os.path.join(base, 'lib', 'python%s' % sys.version[:3], 'site-packages')
prev_sys_path = list(sys.path)
import site
site.addsitedir(site_packages)
sys.real_prefix = sys.prefix
sys.prefix = base
# Move the added items to the front of the path:
new_sys_path = []
for item in list(sys.path):
if item not in prev_sys_path:
new_sys_path.append(item)
sys.path.remove(item)
sys.path[:0] = new_sys_path
Flask 里可以设置一些错误处理页面,示例如下。
@app.errorhandler(404)
def page_not_found():
return "<h1>404</h1>"
Apache
安装完 Apache 后,需要引用 WSGI 模块。此处使用的是 Python 3,需要执行以下命令。
sudo apt-get install libapache2-mod-wsgi-py3
在 Apache 的配置文件 /etc/apache2/sites-available/000-default.conf 里添加配置如下。
<VirtualHost *:80>
ServerName Your.Server.Name
ServerAdmin YourMail@Server.Name
DocumentRoot Your_Web_Root
<Directory Your_Web_Root>
Options Indexes FollowSymlinks
AllowOverride All
WSGIScriptReloading On
</Directory>
WSGIScriptAlias / Your_Web_Root/flask.wsgi
</VirtualHost>
重启 Apache 即可。
如果服务没有运行起来,可以到 Apache 的 error.log 里查看原因。通常可能出错的问题包括 Python 程序问题、Web 目录权限问题、组件版本不对等,可根据错误类型进一步调整程序。