如何在 Web 服务器(例如 localhost)上运行 Python 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20242434/
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
How to run Python scripts on a web server (e.g localhost)
提问by mungaih pk
In my development of Android and Java applications I have been using PHP scripts to interact with an online MySQL database, but now I want to migrate to Python.
在我开发 Android 和 Java 应用程序时,我一直使用 PHP 脚本与在线 MySQL 数据库进行交互,但现在我想迁移到 Python。
How does one run Python scripts on a web server? In my experience with PHP, I have been saving my files under /var/wwwfolder in a Linux environment. Then I just call the file later with a URL of the path. Where do I save my Python scripts?
如何在 Web 服务器上运行 Python 脚本?根据我使用 PHP 的经验,我一直将文件保存/var/www在 Linux 环境中的文件夹下。然后我稍后会使用路径的 URL 调用该文件。我在哪里保存我的 Python 脚本?
回答by pvoosten
Use a web application framework like CherryPy, Django, Webapp2 or one of the many others. For a production setup, you will need to configure the web server to make them work.
使用 Web 应用程序框架,如 CherryPy、Django、Webapp2 或许多其他框架之一。对于生产设置,您需要配置 Web 服务器以使其工作。
Or write CGI programs with Python.
或者用 Python 编写 CGI 程序。
回答by shshank
You can use Flask to run webapps.
您可以使用 Flask 来运行 web 应用程序。
The simple Flask app below will help you get started.
下面的简单 Flask 应用程序将帮助您入门。
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/sampleurl' methods = ['GET'])
def samplefunction():
#access your DB get your results here
data = {"data":"Processed Data"}
return jsonify(data)
if __name__ == '__main__':
port = 8000 #the custom port you want
app.run(host='0.0.0.0', port=port)
Now when you hit http://your.systems.ip:8000/sampleurlyou will get a json response for you mobile app to use.
现在,当您点击时,http://your.systems.ip:8000/sampleurl您将获得一个 json 响应供您的移动应用程序使用。
From within the function you can either do DB reads or file reads, etc.
在该函数中,您可以执行数据库读取或文件读取等操作。
You can also add parameters like this:
您还可以添加如下参数:
@app.route('/sampleurl' methods = ['GET'])
def samplefunction():
required_params = ['name', 'age']
missing_params = [key for key in required_params if key not in request.args.keys()]
if len(missing_params)==0:
data = {
"name": request.argv['name'],
"age": request.argv['age']
}
return jsonify(data)
else:
resp = {
"status":"failure",
"error" : "missing parameters",
"message" : "Provide %s in request" %(missing_params)
}
return jsonify(resp)
To run this save the flask app in a file e.g. myapp.py
要运行它,将烧瓶应用程序保存在一个文件中,例如 myapp.py
Then from terminal run python myapp.py
然后从终端运行 python myapp.py
It will start the server on port 8000 (or as specified by you.)
它将在端口 8000(或您指定的端口)上启动服务器。
Flask's inbuilt server is not recommended for production level use. After you are happy with the app, you might want to look into Nginx + Gunicorn + Flasksystem.
不建议将 Flask 的内置服务器用于生产级别。在您对应用程序感到满意后,您可能想要研究Nginx + Gunicorn + Flask系统。
For detailed instruction on flask you can look at this answer. It is about setting up a webserver on Raspberry pi, but it should work on any linux distro.
有关烧瓶的详细说明,您可以查看此答案。它是关于在 Raspberry pi 上设置网络服务器,但它应该适用于任何 linux 发行版。
Hope that helps.
希望有帮助。
回答by goncalopp
Most web development in python happens using a web framework. This is different than simply having scripts on the server, because the framework has a lot more functionality, such as handling URL routing, HTML templating, ORM, user session management, CSRFprotection, and a lot of other features. This makes it easier to develop web sites, especially since it promotes component reuse, in a OOP fashion.
Python 中的大多数 Web 开发都是使用 Web 框架进行的。这与简单地在服务器上安装脚本不同,因为该框架具有更多功能,例如处理 URL 路由、HTML 模板、ORM、用户会话管理、CSRF保护以及许多其他功能。这使得开发网站变得更加容易,特别是因为它以 OOP 方式促进了组件的重用。
The most popular python web framework is Django. It's a fully-featured, tighly-coupled framework, with lots of documentation available. If you prefer something more modular and easier to customize, I personally recommend Flask. There's also lots of other choices available.
最流行的 Python 网络框架是Django。它是一个功能齐全、紧密耦合的框架,有很多可用的文档。如果你更喜欢更模块化和更容易定制的东西,我个人推荐Flask。还有很多其他选择可用。
With that being said, if all you really want is to run a single, simple python script on a server, you can check this questionfor a simple example using apache+cgi.
话虽如此,如果您真正想要的是在服务器上运行一个简单的 Python 脚本,您可以使用 apache+cgi检查这个问题的一个简单示例。
回答by Octopus
On Apache the simplest way would be to write the python as CGI here is an example:
在 Apache 上,最简单的方法是将 python 编写为 CGI,这里是一个示例:
First create an .htaccess for the web folder that is serving your python:
首先为为您的 Python 提供服务的 web 文件夹创建一个 .htaccess:
AddHandler cgi-script .py
Options +ExecCGI
Then write python that includes some some cgi libraries and outputs headers as well as the content:
然后编写包含一些 cgi 库和输出头以及内容的 python:
#!/usr/bin/python
import cgi
import cgitb
cgitb.enable()
# HEADERS
print "Content-Type:text/html; charset=UTF-8"
print # blank line required at end of headers
# CONTENT
print "<html><body>"
print "Content"
print "</body></html>"
Make sure the file is owned by Apache chown apache. filenameand has the execute bit set chmod +x filename.
确保该文件归 Apache 所有chown apache. filename并设置了执行位chmod +x filename。
There are many significant benefits to actually using a web framework (mentioned in other answers) over this method, but in a localhost web server environment set up for other purposes where you just want to run one or two python scripts, this works well.
与此方法相比,实际使用 Web 框架(在其他答案中提到)有许多显着的好处,但是在为其他目的而设置的 localhost Web 服务器环境中,您只想运行一两个 Python 脚本,这很有效。
Notice I didn't actually utilize the imported cgi library in this script, but hopefully that will direct you to the proper resources.
请注意,我实际上并未在此脚本中使用导入的 cgi 库,但希望这将引导您找到正确的资源。

