Запуск python-скриптов на nginx
Подскажите как. Прочитал про uwsgi — сошел сума, что мне надо зачемто создавать юзера, зачемто держать в хомяке этого юзера .py файлы. Хочу простого, чтоб также как php — файл положил в вебрут, открыл браузером получил вывод. Есть способ простой?
зы. Нет, я не собираюсь запускать джанги, фласки и прочие, и также не хочу всё это ставить.
Зачем тебе это? Неосилятор?
Нет, поднимай uWSGI
Питон это тебе не пыха
21 век, веб-сервер на питоне поднимается за полчаса (с гуглением и чтением доки), nginx как реверс-прокси настраивается за 5 минут.
Откуда, откуда возникают вопросы про uwsgi?
хочу скрипты не из консоли запускать, по ссылке. я не неосилятор. я просто посмотрел на то что предлагается (django+uwsgi) увидел там бред типа
и не увидел здесь обычного питона. даже ставить это гавнецо нет желания, не то что пробовать.
плохо понимаю, зачем мне вебсервер на питоне? я всегото хочу ложить .py файлы в web-root и заходить на них по ссылке. всё, точка.
Натурально, совсем не понимаете.
А исполнять твои .py кто будет? Пушкин? Вот «веб-сервер на питоне» и будет этим заниматься.
А исполнять твои .py кто будет? Пушкин? Вот «веб-сервер на питоне» и будет этим заниматься.
python пусть их и исполняет. на стороне сервера. и делает вывод. кароч, как в php, только python.
Если тебе не нужен FastCGI, а хватит CGI, то юзай Apache,
поделка nginx сама ничего не умеет — даже CGI запускать.
Более того, если тебе веб-сервер нужен под Windows (как тут мне недавно захотели), то nginx в винде работает только через TCP-сокеты, и даже FastCGI под виндой даже получается медленнее CGI под юниксами.
мне нужно сделать по простому. у меня нет приложений использующих web-фреймворки. приложения работают в консоли прекрасно. но мне надоело ходить в консоль при работающем браузере.
вы меня за когото нетого принимаете.
Раньше для такого у Apache был psp — python server pages, работало в стиле php. Кажется сейчас оно устарело и не поддерживается.
Ты не понимаешь во что ввязался, мальчик:
Nginx не имеет встроенной поддержки CGI (вместо этого он поддерживает fastCGI). Типичным решением для этого является запуск Perl script в качестве процесса fastCGI и редактирование файла конфигурации nginx для перенаправления запросов на процесс fastCGI. Это довольно сложное решение, если все, что вы хотите сделать, это запустить CGI script.
Вам нужно использовать nginx для этого решения? Если все, что вы хотите сделать, это выполнить некоторые скрипты Perl CGI, подумайте об использовании Apache или Lighttpd, поскольку они поставляются с модулями CGI, которые будут обрабатывать ваши сценарии CGI изначально и не требуют, чтобы script выполнялся как отдельный процесс. Для этого вам необходимо установить веб-сервер и отредактировать файл конфигурации веб-сервера для загрузки модуля CGI. Для Lighttpd вам нужно будет добавить строку в файл конфигурации, чтобы разрешить обработку файлов CGI. Затем поместите файлы CGI в папку cgi-bin.
Я думал речь об nginx unit пойдет.
Не знаю такого — пукалка Nginx не умеет CGI.
nginx does not support (by design) CGIs. You need an application server for managing them
cgi. cgi. cgi. я честно, даже не знаю, что это (сталкивался с нуждой эти самые cgi настроить чтоб работали, но делал просто по мануалу, не вникая что за нахрен и почему оно всё как-то сделано через задницу, а не так как пхп. вообще, я не понимаю этой всей задницы с чем-то отличным от пхп. только пхп и умеет вот так по простому — сделал файло, положил в вебрут и оно работает. за каким фигом мне нужно эти самые cgi ложить в cgi-bin и запускать оттуда мне тоже непонятно и нет желания понимать. почему не сделают простое — расширение .xyz запускать интерпретатором xyz и всё) ))))) и впринципе мне пофиг, какой будет вебсервер, т.к. это домашний сервачок. пусть это будет апач, ещё что, не важно. главная цель — просто ложить .py в вебрут и иметь вывод.
я не очень шарю, но разве https://unit.nginx.org/howto/flask/ не то что тебе надо ?
из вики — Flask является микрофреймворком для создания вебсайтов на языке Python. В основу статьи положен перевод из официальной документации Flask. Поэтому в ней имеется обращение от первого лица, то есть от создателя фреймворка Армина Ронахера.
нет, я не собираюсь создавать вебсайты или вебприложения и соотвественно не хочу ставить это.
только пхп и умеет вот так по простому — сделал файло, положил в вебрут и оно работает
П-zдишь, PHP так не умеет, и пукалка Nginx так не умеет — это «просто» делает Apache или Lighttpd.
что-то я не понял, как не умеет? а как же оно у меня работает?
Где работает? Через какой веб-сервер?
только пхп и умеет вот так по простому — сделал файло, положил в вебрут и оно работает.
Потому что в PHP встроенный шаблонизатор.
да uwsgi проще паренной репы. С php все хуже. uwsgi умеет не только python
uwsgi-plugin-gccgo — GNU Go plugin for uWSGI uwsgi-plugin-geoip — GeoIP plugin for uWSGI uwsgi-plugin-gevent-python — gevent plugin for uWSGI (Python 2) uwsgi-plugin-glusterfs — GlusterFS storage plugin for uWSGI uwsgi-plugin-graylog2 — graylog2 plugin for uWSGI uwsgi-plugin-greenlet-python — greenlet plugin for uWSGI (Python 2) uwsgi-plugin-jvm-openjdk-8 — Java plugin for uWSGI (OpenJDK 7) uwsgi-plugin-jwsgi-openjdk-8 — JWSGI plugin for uWSGI (OpenJDK 7) uwsgi-plugin-ldap — LDAP plugin for uWSGI uwsgi-plugin-lua5.1 — Lua WSAPI plugin for uWSGI (Lua 5.1) uwsgi-plugin-lua5.2 — Lua WSAPI plugin for uWSGI (Lua 5.2) uwsgi-plugin-luajit — Lua WSAPI plugin for uWSGI (LuaJIT) uwsgi-plugin-mono — Mono/ASP.NET plugin for uWSGI uwsgi-plugin-php — PHP plugin for uWSGI uwsgi-plugin-psgi — Perl PSGI plugin for uWSGI uwsgi-plugin-python — WSGI plugin for uWSGI (Python 2) uwsgi-plugin-python3 — WSGI plugin for uWSGI (Python 3) uwsgi-plugin-rack-ruby2.3 — Rack plugin for uWSGI (ruby2.3) uwsgi-plugin-rados — Ceph/RADOS storage plugin for uWSGI uwsgi-plugin-rbthreads — Ruby native threads plugin for uWSGI (ruby2.3) uwsgi-plugin-ring-openjdk-8 — Closure/Ring plugin for uWSGI (OpenJDK 7) uwsgi-plugin-router-access — Access router plugin for uWSGI uwsgi-plugin-servlet-openjdk-8 — JWSGI plugin for uWSGI (OpenJDK 7) uwsgi-plugin-sqlite3 — SQLite 3 configurations plugin for uWSGI uwsgi-plugin-tornado-python — tornado plugin for uWSGI (Python 2) uwsgi-plugin-v8 — JavaScript V8 plugin for uWSGI uwsgi-plugin-xslt — XSLT request plugin for uWSGI
Не ну можно проксировать http или вообще большинство фреймворков сами умеют http php умеет? Хотя это способ себе прострелить голову.
uwsgi умеет много процессов, потоков. Умеет перезапускать если слишком долго пашет.
Пойми одну простую вещь: пукалка Nginx сама ничего не умеет, она может только перенаправлять веб-запросы на сервера приложений. Причем может это только через хитровы-банные протоколы типа FastCGI.
Сырой веб-трафик (CGI) со скриптов она брать не умеет, ибо тупа как пробка.
нет, я не собираюсь создавать вебсайты или вебприложения и соотвественно не хочу ставить это.
Вот сейчас совсем не понятно. Зачем тебе NGINX если ты «я не собираюсь создавать вебсайты или вебприложения»
Ты еще PostgreSQL поставь если тебе БД не нужно
ок. что мне поставить (какой сервер приложений) чтоб всё было по простому. без установки любых фреймворков (по крайней мере до поры, пока я не захочу использовать этот фреймвор). без cgi-bin, без добавления юзеров, просто ложа файлы в вебрут и открывая их в браузере хочу видеть результат выполнения.
Зачем тебе NGINX если ты «я не собираюсь создавать вебсайты или вебприложения»
есть python скрипт, который я запуска в консоли. надоело открывать консоль, при открытом браузере. хочу видеть результат выполенния скрипта открыв http://example.org/python.py и конечно же, скрипт должен запуститься и показать результат выполнения тогда, когда я обращусь к нему. и от этой хотелки — оно не становится вебприложением.
сделай по крону запуск скрипта, который генерит статический html.
поглядел наискосок конфиг, не понял, мне что, каждый python скрипт нужно объявлять как отдельное вебприложение? нифига не то что я хочу.
что мне поставить (какой сервер приложений) чтоб всё было по простому
по-простому с Nginx не получится, если ты ещё не врубился — ибо это недоделанная пускалка.
А по хитрому — через uwsgi
Но этого мало. Насколько я понял, сам python-движок тоже должен поддерживать FastCGI и уметь разговаривать с uwsgi по этому протоколу.
У тебя какой пистон-движок?
Если движка нет и ты используешь сырой пистон, то гугли по словам «direct cgi uwsgi», uwsgi умеет вызывать скрипты, но нужно задавать его вызов (в конфигах) как-то так:
А потом натравливать nginx на UNIX-socket в слюниксе (mysite.sock) или на TCP-сокет (:8000) в вантузе.
Вот тебе больше параметров из моих черновиков:
Quickstart for Python/WSGI applicationsВ¶
This quickstart will show you how to deploy simple WSGI applications and common web frameworks.
Python here is meant as CPython, for PyPy you need to use the specific plugin: The PyPy plugin , Jython support is under construction.
You need at least uWSGI 1.4 to follow the quickstart. Anything older is no longer maintained and is highly buggy!
Installing uWSGI with Python supportВ¶
When you start learning uWSGI, try to build from official sources: using distribution-supplied packages may bring you plenty of headaches. When things are clear, you can use modular builds (like the ones available in your distribution).
uWSGI is a (big) C application, so you need a C compiler (like gcc or clang) and the Python development headers.
On a Debian-based distro an
You have various ways to install uWSGI for Python:
using the network installer
(this will install the uWSGI binary into /tmp/uwsgi , feel free to change it).
via downloading a source tarball and “making” it
(after the build you will have a uwsgi binary in the current directory).
Installing via your package distribution is not covered (would be impossible to make everyone happy), but all of the general rules apply.
One thing you may want to take into account when testing this quickstart with distro-supplied packages, is that very probably your distribution has built uWSGI in modular way (every feature is a different plugin that must be loaded). To complete this quickstart, you have to prepend —plugin python,http to the first series of examples, and —plugin python when the HTTP router is removed (if this doesn’t make sense to you, just continue reading).
The first WSGI applicationВ¶
Let’s start with a simple “Hello World” example:
(save it as foobar.py ).
As you can see, it is composed of a single Python function. It is called “application” as this is the default function that the uWSGI Python loader will search for (but you can obviously customize it).
Deploy it on HTTP port 9090В¶
Now start uWSGI to run an HTTP server/router passing requests to your WSGI application:
Do not use —http when you have a frontend webserver or you are doing some form of benchmark, use —http-socket . Continue reading the quickstart to understand why.
Adding concurrency and monitoringВ¶
The first tuning you would like to make is adding concurrency (by default uWSGI starts with a single process and a single thread).
You can add more processes with the —processes option or more threads with the —threads option (or you can have both).
This will spawn 4 processes (each with 2 threads), a master process (will respawn your processes when they die) and the HTTP router (seen before).
One important task is monitoring. Understanding what is going on is vital in production deployment. The stats subsystem allows you to export uWSGI’s internal statistics as JSON:
Make some request to your app and then telnet to the port 9191, you’ll get lots of fun information. You may want to use “uwsgitop” (just pip install it), which is a top-like tool for monitoring instances.
Bind the stats socket to a private address (unless you know what you are doing), otherwise everyone could access it!
Putting behind a full webserverВ¶
Even though uWSGI HTTP router is solid and high-performance, you may want to put your application behind a fully-capable webserver.
uWSGI natively speaks HTTP, FastCGI, SCGI and its specific protocol named “uwsgi” (yes, wrong naming choice). The best performing protocol is obviously uwsgi, already supported by nginx and Cherokee (while various Apache modules are available).
A common nginx config is the following:
This means “pass every request to the server bound to port 3031 speaking the uwsgi protocol”.
Now we can spawn uWSGI to natively speak the uwsgi protocol:
If you’ll run ps aux , you will see one process less. The HTTP router has been removed as our “workers” (the processes assigned to uWSGI) natively speak the uwsgi protocol.
If your proxy/webserver/router speaks HTTP, you have to tell uWSGI to natively speak the http protocol (this is different from –http that will spawn a proxy by itself):
Automatically starting uWSGI on bootВ¶
If you are thinking about firing up vi and writing an init.d script for spawning uWSGI, just sit (and calm) down and make sure your system doesn’t offer a better (more modern) approach first.
Each distribution has chosen a startup system ( Upstart , Systemd …) and there are tons of process managers available (supervisord, god, monit, circus…).
uWSGI will integrate very well with all of them (we hope), but if you plan to deploy a big number of apps check the uWSGI Emperor — it is more or less the dream of every devops engineer.
Deploying DjangoВ¶
Django is very probably the most used Python web framework around. Deploying it is pretty easy (we continue our configuration with 4 processes with 2 threads each).
We suppose the Django project is in /home/foobar/myproject :
(with —chdir we move to a specific directory). In Django this is required to correctly load modules.
Argh! What the hell is this?! Yes, you’re right, you’re right… dealing with such long command lines is unpractical, foolish and error-prone. Never fear! uWSGI supports various configuration styles. In this quickstart we will use .ini files.
If the file /home/foobar/myproject/myproject/wsgi.py (or whatever you have called your project) does not exist, you are very probably using an old ( env , module and the pythonpath ( .. allow us to reach the myproject.settings module).
Deploying FlaskВ¶
Flask is a popular Python web microframework.
Save the following example as myflaskapp.py :
Flask exports its WSGI function (the one we called “application” at the beginning of this quickstart) as “app”, so we need to instruct uWSGI to use it. We still continue to use the 4 processes/2 threads and the uwsgi socket as the base:
(the only addition is the —callable option).
Deploying web2pyВ¶
Again a popular choice. Unzip the web2py source distribution on a directory of choice and write a uWSGI config file:
On recent web2py releases you may need to copy the wsgihandler.py script out of the handlers directory.
We used the HTTP router again. Just go to port 9090 with your browser and you will see the web2py welcome page.
Click on the administrative interface and… oops, it does not work as it requires HTTPS. Do not worry, the uWSGI router is HTTPS-capable (be sure you have OpenSSL development headers: install them and rebuild uWSGI, the build system will automatically detect it).
First of all generate your key and certificate:
Now you have 2 files (well 3, counting the foobar.csr ), foobar.key and foobar.crt . Change the uWSGI config:
Re-run uWSGI and connect to port 9090 using https:// with your browser.
A note on Python threadsВ¶
If you start uWSGI without threads, the Python GIL will not be enabled, so threads generated by your application will never run. You may not like that choice, but remember that uWSGI is a language-independent server, so most of its choices are for maintaining it “agnostic”.
But do not worry, there are basically no choices made by the uWSGI developers that cannot be changed with an option.
If you want to maintain Python threads support without starting multiple threads for your application, just add the —enable-threads option (or enable-threads = true in ini style).
VirtualenvsВ¶
uWSGI can be configured to search for Python modules in a specific virtualenv.
Just add virtualenv =
Security and availabilityВ¶
Always avoid running your uWSGI instances as root. You can drop privileges using the uid and gid options:
If you need to bind to privileged ports (like 443 for HTTPS), use shared sockets. They are created before dropping privileges and can be referenced with the =N syntax, where N is the socket number (starting from 0):
A common problem with webapp deployment is “stuck requests”. All of your threads/workers are stuck (blocked on request) and your app cannot accept more requests. To avoid that problem you can set a harakiri timer. It is a monitor (managed by the master process) that will destroy processes stuck for more than the specified number of seconds (choose harakiri value carefully). For example, you may want to destroy workers blocked for more than 30 seconds:
In addition to this, since uWSGI 1.9, the stats server exports the whole set of request variables, so you can see (in realtime) what your instance is doing (for each worker, thread or async core).
OffloadingВ¶
The uWSGI offloading subsystem allows you to free your workers as soon as possible when some specific pattern matches and can be delegated to a pure-c thread. Examples are sending static file from the file system, transferring data from the network to the client and so on.
Offloading is very complex, but its use is transparent to the end user. If you want to try just add —offload-threads where is the number of threads to spawn (1 per CPU is a good value to start with).
When offload threads are enabled, all of the parts that can be optimized will be automatically detected.
Bonus: multiple Python versions for the same uWSGI binaryВ¶
As we have seen, uWSGI is composed of a small core and various plugins. Plugins can be embedded in the binary or loaded dynamically. When you build uWSGI for Python, a series of plugins plus the Python one are embedded in the final binary.
This could be a problem if you want to support multiple Python versions without building a binary for each one.
The best approach would be having a little binary with the language-independent features built in, and one plugin for each Python version that will be loaded on-demand.
In the uWSGI source directory:
This will build a uwsgi binary with all the default plugins built-in except the Python one.
Now, from the same directory, we start building Python plugins:
You will end up with three files: python34_plugin.so , python27_plugin.so , python26_plugin.so . Copy these into your desired directory. (By default, uWSGI searches for plugins in the current working directory.)
Now in your configurations files you can simply add (at the very top) the plugins-dir and plugin directives.
This will load the python26_plugin.so plugin library from the directory into which you copied the plugins.
And now…¶
You should already be able to go into production with such few concepts, but uWSGI is an enormous project with hundreds of features and configurations. If you want to be a better sysadmin, continue reading the full docs.
© Copyright 2012-2016, uWSGI Revision a650304d .