Как установить pip socket windows
Перейти к содержимому

Как установить pip socket windows

  • автор:

Как перестать беспокоиться и установить Python-проект другу под Windows

Итак, вы закончили свою первую версию опенсорс проекта на Питоне, выложили её на Гитхаб, и даже написали честный ридми: «Требуется Python 3.10, поставьте зависимости через pip install -r requirements.txt «.

И. через какое‑то время вам звонит пользователь друг с вопросом: «Слушай, интересный проект, а как его под Windows поставить?»

Собственно, с этого момента у вас есть 3 варианта:

  1. Попытаться сэкономить всем время и попробовать упаковать ваш проект в EXE‑файл через утилиты типа pyinstaller или Auto PY to EXE. Минус: при сколь‑нибудь сложных зависимостях нужно будет ковыряться довольно долго, чтобы заставить EXE заработать. Второй минус: как вы думаете, на кого ляжет почетная обязанность собирать EXE‑шники после каждого апдейта кода?
  2. Попытаться объяснить другу, что такое python, GIT и как всё это поставить. Минус: возможны проблемы в отношениях с другом:))) (Вариант: поставить всё самому через дистанционный доступ, но он требует слишком много времени если пользователей друзей больше 5)
  3. Дописать под себя набор BAT‑файлов, о которых пойдет речь в статье, и которые:
    1. ставят сами Python и GIT в локальную папку проекта (в стиле conda);
    2. выкачивают свежую версию с Гитхаба (а также апдейтят её при необходимости);
    3. ставят нужные зависимости;
    4. можно прописать несколько сценариев запуска приложения;
    5. установленный проект можно перемещать в другие папки и между компами.

    Как я эти батники нашел

    Есть такой интересный опенсорс проект, который позволяет запускать текстовые нейросети на локальном компьютере с веб‑интерфейсом: https://github.com/oobabooga/text‑generation‑webui

    Проекты с нейросетями, как правило, это проекты с очень большим числом нетривиальных зависимостей. Например:

    • Вам нужно знать, нужно ли ставить версию torch с GPU ускорением от NVIDIA, или же надо ставить CPU‑версию.
    • Часто нужно скачивать какие‑то кастомные дополнительные Github‑проекты библиотеки.
    • Надо ставить нетривиальные версии библиотек (проект выше, например, использует кастомную сборку bitsandbytes под Windows, которая позволяет запускать 4-битные нейросети, требующие меньше памяти)

    И я был сильно удивлен, когда нашел проект от того же пользователя под названием one‑click‑installers, который решал все эти проблемы установки буквально в несколько BAT‑файлов.

    Собственно, я его установил (все заработало с первого раза), разобрался в BAT‑файлах, и они меня так впечатлили своей компактностью, что я даже достаточно быстро сделал подобный компактный инсталлятор для своего голосового помощника Ирины.

    Как это работает и как это настроить

    В качестве базового проекта рекомендую взять мой инсталлятор, а за нетривиальными случаями обращаться к оригинальному one‑click‑installer.

    Итак, есть два основных файла:

    1. Скачивает проект micromamba (компактная замена conda). (Вначале выводится предупреждение — путь не должен содержать пробелов и нелатинских букв/цифр.)
    2. Устанавливает указанные пакеты (в частности, я указываю python3.10 и git; в моем BAT‑файле есть еще выбор, установить ли тяжелый torch для Silero TTS, но вы можете этот выбор убрать) в installer_files.
    3. Активирует окружение
    4. Если репозитория вашего проекта ещё не существует — клонирует его с Гитхаба; если уже существует — пытается обновить с помощью git pull.
    5. Устанавливает или обновляет зависимости через call python -m pip install -r requirements.txt —upgrade . (У меня используются кастомные зависимости в call python ‑m pip install ‑r requirements_exe_runner.txt ‑upgrade, так что не забудьте поправить для своего проекта)

    Собственно, после install в идеале наш проект полностью готов к работе.

    run предельно простой:

    1. Он инициализирует окружение с нужными зависимостями
    2. Запускает нужный питон‑файл через call python run.py (или что вы там укажете)

    Также в проекте существует micromamba‑cmd.bat, который позволяет в интерактивном режиме зайти в текущее окружение и что‑то там подправить (например, поставить новые зависимости ручками если сильно нужно).

    Переносимость

    Установка переносимая; но после переноса в другое место будет выдавать ошибку «Micromamba not found» — потому что сформированные BAT‑файлы Micromamba содержат абсолютные пути.

    Для решения проблемы после переноса нужно удалить все BAT‑файлы из installer_files\mamba\condabin и запустить run.bat — BAT‑файлы будут перегенерированы.

    Выводы

    install.bat выполняет основную часть установки, ставя зависимости через Интернет, позволяет быстро обновлять проект до последней Git‑версии, и занимает всего 90 строк кода.

    Вот я с ним поработал и могу сказать — поправить его под свой проект занимает где‑то полчаса‑час (ну, вместе с тестированием мелочей, конечно).

    По‑моему, очень удобно.

    ap75 / PyBluez.txt

    This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

    Python sockets AF_BLUETOOTH не работает под Windows, поэтому используем PyBluez на основе .Net
    1) Скачать установщик Visual Studio Community
    2) Запустить его, он загрузит и установит необходимые для своей работы модули
    3) Выбираем «Python development» («Разработка на Python»), «Visual C++ build tools» и «Universal Windows Platform build tools», запускаем процесс загрузки и установки
    4) В рабочем каталоге выполняем (чтобы создать виртуальное окружение venv при помощи модуля venv)
    python3 -m venv venv
    Активируем:
    venv\Scripts\activate.bat
    5) Там же (чтобы установить PyBluez):
    pip install PyBluez-win10
    на основе: https://github.com/pybluez/pybluez/issues/180#issuecomment-448102727
    но там:
    git clone https://github.com/pybluez/pybluez
    cd pybluez
    python setup.py install

    Хостинг Python проекта — настройка uWSGI по шагам

    Разберем по шагам процесс и детали настройки хостинга для Python проекта с использованием uWSGI на примере Django.

    Кроме nginx и uWSGI на сервере вам понадобятся PIP и Virtualenv-wrapper, а также Python dev packages.

    Я рекомендую VPS от DigitalOcean. Удобное управление, низкие цены — идеально для хостинга своего проекта. Плюс сервера в этом облаке в несколько раз быстрее чем в Amazon EC2 при равной цене или даже меньшей в DigitalOcean.

    digitalocean vps for django hosting

    Регистрация по этой ссылке даст 10$ в кредит:

    Этого достаточно для бесплатной работы сервера 2 месяца.

    Принцип работы uWSGI

    A web server faces the outside world. It can serve files (HTML, images, CSS, etc) directly from the file system. However, it can’t talk directly to Django applications; it needs something that will run the application, feed it requests from web clients (such as browsers) and return responses.

    A Web Server Gateway Interface — WSGI — does this job. WSGI is a Python standard.

    uWSGI is a WSGI implementation. In this tutorial we will set up uWSGI so that it creates a Unix socket, and serves responses to the web server via the WSGI protocol. At the end, our complete stack of components will look like this:

    the web client the web server the socket uwsgi Django

    Подготовка к установке uWSGI

    Установка pip, python-dev, virtualenvwrapper

    Установка Python dev packages

    apt-get install python-dev
    apt-get install pip
    pip install virtualenvwrapper

    Создание виртуального окружения

    Make sure you are in a virtualenv for the software we need to install (we will describe how to install a system-wide uwsgi later):

    virtualenv uwsgi-tutorial cd uwsgi-tutorial source bin/activate
    mkproject uwsgi-tutorial

    Установка Django

    Install Django into your virtualenv, create a new project, and cd into the project:

    pip install Django django-admin.py startproject mysite cd mysite

    Про домен и порт

    In this tutorial we will call your domain example.com. Substitute your own FQDN or IP address.

    Throughout, we’ll using port 8000 for the web server to publish on, just like the Django runserver does by default. You can use whatever port you want of course, but I have chosen this one so it doesn’t conflict with anything a web server might be doing already.

    Установка и начальная настройка uWSGI

    Установка uWSGI в виртуальном окружении

    pip install uwsgi

    Of course there are other ways to install uWSGI, but this one is as good as any. Remember that you will need to have Python development packages installed. In the case of Debian, or Debian-derived systems such as Ubuntu, what you need to have installed is pythonX.Y-dev, where X.Y is your version of Python.

    Проверка работы

    Create a file called test.py:

    # test.py def application(env, start_response): start_response('200 OK', [('Content-Type','text/html')]) return "Hello World"
    uwsgi --http :8000 --wsgi-file test.py

    The options mean:

    • http :8000: use protocol http, port 8000
    • wsgi-file test.py: load the specified file, test.py

    This should serve a ‘hello world’ message directly to the browser on port 8000. Visit:

    http://example.com:8000

    to check. If so, it means the following stack of components works:

    the web client uWSGI Python

    Проверка работы Django проекта

    Now we want uWSGI to do the same thing, but to run a Django site instead of the test.py module.

    If you haven’t already done so, make sure that your mysite project actually works:

    python manage.py runserver 0.0.0.0:8000

    And if it that works, run it using uWSGI:

    uwsgi --http :8000 --wsgi-file barons/wsgi.py
    • module mysite.wsgi: load the specified wsgi module

    Point your browser at the server; if the site appears, it means uWSGI is able serve your Django application from your virtualenv, and this stack operates correctly:

    the web client uWSGI Django

    Now normally we won’t have the browser speaking directly to uWSGI. That’s a job for the webserver, which will act as a go-between.

    Настройка nginx

    Установка nginx

    sudo apt-get install nginx sudo /etc/init.d/nginx start # start nginx

    And now check that the nginx is serving by visiting it in a web browser on port 80 — you should get a message from nginx: “Welcome to nginx!”. That means these components of the full stack are working together:

    the web client the web server

    If something else is already serving on port 80 and you want to use nginx there, you’ll have to reconfigure nginx to serve on a different port. For this tutorial though, we’re going to be using port 8000.

    Настройка вашего сайта в nginx

    Скачайте файл uwsgi_params с https://github.com/nginx/nginx/blob/master/conf/uwsgi_params, либо просто создайте его, поместив туда текст:

    uwsgi_param QUERY_STRING $query_string; uwsgi_param REQUEST_METHOD $request_method; uwsgi_param CONTENT_TYPE $content_type; uwsgi_param CONTENT_LENGTH $content_length; uwsgi_param REQUEST_URI $request_uri; uwsgi_param PATH_INFO $document_uri; uwsgi_param DOCUMENT_ROOT $document_root; uwsgi_param SERVER_PROTOCOL $server_protocol; uwsgi_param HTTPS $https if_not_empty; uwsgi_param REMOTE_ADDR $remote_addr; uwsgi_param REMOTE_PORT $remote_port; uwsgi_param SERVER_PORT $server_port; uwsgi_param SERVER_NAME $server_name;

    Copy it into your project directory. In a moment we will tell nginx to refer to it.

    Now create a file called mysite_nginx.conf, and put this in it:

    # mysite_nginx.conf # the upstream component nginx needs to connect to upstream django < # server unix:///path/to/your/mysite/mysite.sock; # for a file socket server 127.0.0.1:8001; # for a web port socket (we'll use this first) ># configuration of the server server < # the port your site will be served on listen 8000; # the domain name it will serve for server_name .example.com; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media < alias /path/to/your/mysite/mysite/media; # your Django project's media files - amend as required >location /static < alias /path/to/your/mysite/mysite/static; # your Django project's static files - amend as required ># Finally, send all non-media requests to the Django server. location / < uwsgi_pass django; include /path/to/your/mysite/uwsgi_params; # the uwsgi_params file you installed >>

    This conf file tells nginx to serve up media and static files from the filesystem, as well as handle requests that require Django’s intervention. For a large deployment it is considered good practice to let one server handle static/media files, and another handle Django applications, but for now, this will do just fine.

    Symlink to this file from /etc/nginx/sites-enabled so nginx can see it:

    sudo ln -s ~/path/to/your/mysite/mysite_nginx.conf /etc/nginx/sites-enabled/

    Проверка работы nginx

    sudo /etc/init.d/nginx restart

    To check that media files are being served correctly, add an image called media.png to the/path/to/your/project/project/media directory, then visithttp://example.com:8000/media/media.png — if this works, you’ll know at least that nginx is serving files correctly.

    It is worth not just restarting nginx, but actually stopping and then starting it again, which will inform you if there is a problem, and where it is.

    Тест nginx и uWSGI с test.py

    Let’s get nginx to speak to the “hello world” test.py application.

    uwsgi --socket :8001 --wsgi-file test.py

    This is nearly the same as before, except this time one of the options is different:

    • socket :8001: use protocol uwsgi, port 8001

    nginx meanwhile has been configured to communicate with uWSGI on that port, and with the outside world on port 8000. Visit:

    to check. And this is our stack:

    the web client the web server the socket uWSGI Python

    Meanwhile, you can try to have a look at the uswgi output at http://example.com:8001 — but quite probably, it won’t work because your browser speaks http, not uWSGI, though you should see output from uWSGI in your terminal.

    Использование Unix sockets вместо сетевого порта

    So far we have used a TCP port socket, because it’s simpler, but in fact it’s better to use Unix sockets than ports — there’s less overhead.

    Edit mysite_nginx.conf, changing it to match:

    server unix:///path/to/your/mysite/mysite.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first)

    and restart nginx.

    Runs uWSGI again:

    uwsgi --socket mysite.sock --wsgi-file test.py

    This time the socket option tells uWSGI which file to use.

    Если не заработало

    Check your nginx error log(/var/log/nginx/error.log). If you see something like:

    connect() to unix:///path/to/your/mysite/mysite.sock failed (13: Permission denied)

    then probably you need to manage the permissions on the socket so that nginx is allowed to use it.

    uwsgi --socket mysite.sock --wsgi-file test.py --chmod-socket=666 # (very permissive)

    You may also have to add your user to nginx’s group (which is probably www-data), or vice-versa, so that nginx can read and write to your socket properly.

    It’s worth keeping the output of the nginx log running in a terminal window so you can easily refer to it while troubleshooting.

    Запуск приложения Django с uswgi и nginx

    Let’s run our Django application:

    uwsgi --socket mysite.sock --module mysite.wsgi --chmod-socket=666

    Now uWSGI and nginx should be serving up not just a “Hello World” module, but your Django project.

    Настройка uWSGI для запуска через .ini файл

    We can put the same options that we used with uWSGI into a file, and then ask uWSGI to run with that file. It makes it easier to manage configurations.

    Create a file called `mysite_uwsgi.ini`:

    # mysite_uwsgi.ini file [uwsgi] # Django-related settings # the base directory (full path) chdir = /path/to/your/project # Django's wsgi file module = project.wsgi # the virtualenv (full path) home = /path/to/virtualenv # process-related settings # master master = true # maximum number of worker processes processes = 10 # the socket (use the full path to be safe socket = /path/to/your/project/mysite.sock # . with appropriate permissions - may be needed # chmod-socket = 664 # clear environment on exit vacuum = true

    And run uswgi using this file:

    uwsgi --ini mysite_uwsgi.ini # the --ini option is used to specify a file

    Once again, test that the Django site works as expected.

    Запуск uwsgi в режиме демона

    Чтобы запустить uwsgi в режиме демона, создайте каталог /var/log/uwsgi и добавьте в файл конфигурации строку:

    daemonize=/var/log/uwsgi/yourproject.log

    После этого uwsgi будет использовать указанный файл для вывода всех сообщений. Чтобы просмотреть вывод, запустите в консоли

    tail -f /var/log/uwsgi/yourproject.log

    Завершение настройки веб-сервера

    Установка uWSGI в системе

    So far, uWSGI is only installed in our virtualenv; we’ll need it installed system-wide for deployment purposes.

    Deactivate your virtualenv:

    deactivate

    and install uWSGI system-wide:

    sudo pip install uwsgi # Or install LTS (long term support). pip install http://projects.unbit.it/downloads/uwsgi-lts.tar.gz

    The uWSGI wiki describes several installation procedures. Before installing uWSGI system-wide, it’s worth considering which version to choose and the most apppropriate way of installing it.

    Check again that you can still run uWSGI just like you did before:

    uwsgi --ini mysite_uwsgi.ini # the --ini option is used to specify a file

    Emperor mode

    uWSGI can run in ‘emperor’ mode. In this mode it keeps an eye on a directory of uWSGI config files, and will spawn instances (‘vassals’) for each one it finds.

    Whenever a config file is amended, the emperor will automatically restart the vassal.

    # create a directory for the vassals sudo mkdir /etc/uwsgi sudo mkdir /etc/uwsgi/vassals # symlink from the default config directory to your config file sudo ln -s /path/to/your/mysite/mysite_uwsgi.ini /etc/uwsgi/vassals/ # run the emperor uwsgi --emperor /etc/uwsgi/vassals --uid www-data --gid www-data

    You may need to run uWSGI with sudo:

    sudo uwsgi --emperor /etc/uwsgi/vassals --uid www-data --gid www-data

    The options mean:

    • emperor: where to look for vassals (config files)
    • uid: the user id of the process once it’s started
    • gid: the group id of the process once it’s started

    Check the site; it should be running.

    Автозапуск uWSGI при загрузке сервере

    The last step is to make it all happen automatically at system startup time.

    Edit /etc/rc.local and add:

    /usr/local/bin/uwsgi --emperor /etc/uwsgi/vassals --uid www-data --gid www-data

    before the line “exit 0”.

    And that should be it!

    Дальнейшая настройка веб-сервера

    It is important to understand that this has been a tutorial, to get you started. You do need to read the nginx and uWSGI documentation, and study the options available before deployment in a production environment.

    Both nginx and uWSGI benefit from friendly communities, who are able to offer invaluable advice about configuration and usage.

    nginx

    General configuration of nginx is not within the scope of this tutorial though you’ll probably want to it to listen on port 80, not 8000, for a production website.

    You also ought to consider at having a separate server for non-Django serving, of static files for example.

    uWSGI

    uWSGI supports multiple ways to configure it. See uWSGI’s documentation and examples.

    Some uWSGI options have been mentioned in this tutorial; others you ought to look at for a deployment in production include (listed here with example settings):

    env = DJANGO_SETTINGS_MODULE=mysite.settings # set an environment variable pidfile = /tmp/project-master.pid # create a pidfile harakiri = 20 # respawn processes taking more than 20 seconds limit-as = 128 # limit the project to 128 MB max-requests = 5000 # respawn processes after serving 5000 requests daemonize = /var/log/uwsgi/yourproject.log # background the process & log

    Running uWSGI via Upstart

    Upstart is the init system of Ubuntu-like distributions.

    It is based on declarative configuration files – not shell scripts of yore – that are put in the /etc/init directory.

    A simple script (/etc/init/uwsgi.conf)

    # simple uWSGI script description "uwsgi tiny instance" start on runlevel [2345] stop on runlevel [06] exec uwsgi --master --processes 4 --die-on-term --socket :3031 --wsgi-file /var/www/myapp.wsgi

    Using the Emperor

    A better approach than init files for each app would be to only start an Emperor via Upstart and let it deal with the rest.

    # Emperor uWSGI script description "uWSGI Emperor" start on runlevel [2345] stop on runlevel [06] exec uwsgi --master --die-on-term --emperor /etc/uwsgi

    What is –die-on-term?

    By default uWSGI maps the SIGTERM signal to “a brutal reload procedure”.

    However, Upstart uses SIGTERM to completely shutdown processes. die-on-term inverts the meanings of SIGTERM and SIGQUIT to uWSGI.

    The first will shutdown the whole stack, the second one will brutally reload it.

    Опубликовано 06.08.2013 16.10.2016 Автор Сергей Шармазанов Рубрики Без рубрики

    Хостинг Python проекта — настройка uWSGI по шагам: 4 комментария

    А пост мог бы получиться отличный. Но неясно для носителей какого языка он писан. 50 / 50? Время позднее и в английские буковки вчитываться лень, а перевести ты не удосужился. С таким же успехом можно было кинуть ссылку на документацию.

    Установка и настройка¶

    Перед началом установки необходимо произвести настройку окружения . Все команды выполняются только от суперпользователя .

    sudo -i 

    Для Linux¶

    Имеется поддержка аутентификации пользователя с использованием смарт-карты. Подробнее здесь .

    1. Установите пакет RSclient:
    2. из репозитория Python-пакетов:
    pip3 install rs-client 

    Для Astra Linux 1.7¶

    Для установки RSclient на Astra Linux выполните следующее:

    1. Подключите предоставленный Вам репозиторий с пакетами AccentOs.
    2. Установите пакет командой:

    sudo apt install -y aos-rs-client 

    Функционал получения виртуальных машин по тикетам Kerberos на Для Astra Linux 1.7 доступен только при установке пакета через pip.

    Для корректной установки RSclient через pip на Astra Linux 1.7 выполните следующее:

    1. Подключите представленные Вам репозитории с пакетами AccentOs для Astra Linux 1.7.
    2. Установите пакеты, необходимые для Linux .
    3. Дополнительно установите необходимые для работы пакеты командой:

    apt install python3-pyside2.qt3dcore python3-pyside2.qt3dinput python3-pyside2.qt3dlogic python3-pyside2.qt3drender python3-pyside2.qtconcurrent \ python3-pyside2.qtcore python3-pyside2.qtgui python3-pyside2.qthelp python3-pyside2.qtlocation python3-pyside2.qtmultimedia python3-pyside2.qtmultimediawidgets \ python3-pyside2.qtnetwork python3-pyside2.qtopengl python3-pyside2.qtpositioning python3-pyside2.qtprintsupport python3-pyside2.qtqml python3-pyside2.qtquick \ python3-pyside2.qtquickwidgets python3-pyside2.qtscript python3-pyside2.qtscripttools python3-pyside2.qtsensors python3-pyside2.qtsql python3-pyside2.qtsvg \ python3-pyside2.qttest python3-pyside2.qttexttospeech python3-pyside2.qtuitools python3-pyside2.qtwebchannel python3-pyside2.qtwebenginecore \ python3-pyside2.qtwebenginewidgets python3-pyside2.qtwebsockets python3-pyside2.qtwidgets python3-pyside2.qtx11extras python3-pyside2.qtxml python3-pyside2.qtxmlpatterns 
    sudo ln -s /usr/lib/x86_64-linux-gnu/libxcb-util.so.0 /usr/lib/x86_64-linux-gnu/libxcb-util.so.1 
    pip3 install -y aos-rs-client 

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *