GithubHelp home page GithubHelp logo

pypiserver / pypiserver Goto Github PK

View Code? Open in Web Editor NEW
1.7K 38.0 293.0 4.96 MB

Minimal PyPI server for uploading & downloading packages with pip/easy_install

License: Other

Python 96.98% Shell 1.84% HTML 0.29% Dockerfile 0.73% Makefile 0.17%

pypiserver's Introduction

pypi server logo

pypiserver - minimal PyPI server for use with pip/easy_install

pypi badge ci workflow Generic badge Generic badge

name description
Version 2.1.1
Date: 2024-04-25
Source https://github.com/pypiserver/pypiserver
PyPI https://pypi.org/project/pypiserver/
Tests https://github.com/pypiserver/pypiserver/actions
Maintainers Kostis Anagnostopoulos [email protected], Matthew Planchard [email protected], Dmitrii Orlov [email protected], Someone new? We are looking for new maintainers! #397
License zlib/libpng + MIT
Community https://pypiserver.zulipchat.com

Chat with us on Zulip!

pypiserver is a minimal PyPI compatible server for pip or easy_install. It is based on bottle and serves packages from regular directories. Wheels, bdists, eggs and accompanying PGP-signatures can be uploaded either with pip, setuptools, twine, pypi-uploader, or simply copied with scp.

Note The official software powering PyPI is Warehouse. However, Warehouse is fairly specialized to be pypi.org's own software, and should not be used in other contexts. In particular, it does not officially support being used as a custom package index by users wishing to serve their own packages.

pypiserver implements the same interfaces as PyPI, allowing standard Python packaging tooling such as pip and twine to interact with it as a package index just as they would with PyPI, while making it much easier to get a running index server.

pypiserver

Table of Contents

Quickstart Installation and Usage

pypiserver works with Python 3.6+ and PyPy3.

Older Python versions may still work, but they are not tested.

For legacy Python versions, use pypiserver-1.x series. Note that these are not officially supported, and will not receive bugfixes or new features.

Tip

The commands below work on a unix-like operating system with a posix shell. The '~' character expands to user's home directory.

If you're using Windows, you'll have to use their "Windows counterparts". The same is true for the rest of this documentation.

  1. Install pypiserver with this command
   pip install pypiserver                # Or: pypiserver[passlib,cache]
   mkdir ~/packages                      # Copy packages into this directory.

See also Alternative Installation methods

  1. Copy some packages into your ~/packages folder and then get your pypiserver up and running
   pypi-server run -p 8080 ~/packages &      # Will listen to all IPs.
  1. From the client computer, type this
   # Download and install hosted packages.
   pip install --extra-index-url http://localhost:8080/simple/ ...

   # or
   pip install --extra-index-url http://localhost:8080 ...

   # Search hosted packages.
   pip search --index http://localhost:8080 ...

   # Note that pip search does not currently work with the /simple/ endpoint.

See also Client-side configurations for avoiding tedious typing.

  1. Enter pypi-server -h in the cmd-line to print a detailed usage message
usage: pypi-server [-h] [-v] [--log-file FILE] [--log-stream STREAM]
                   [--log-frmt FORMAT] [--hash-algo HASH_ALGO]
                   [--backend {auto,simple-dir,cached-dir}] [--version]
                   {run,update} ...

start PyPI compatible package server serving packages from PACKAGES_DIRECTORY. If PACKAGES_DIRECTORY is not given on the command line, it uses the default ~/packages. pypiserver scans this directory recursively for packages. It skips packages and directories starting with a dot. Multiple package directories may be specified.

positional arguments:
  {run,update}
    run                 Run pypiserver, serving packages from
                        PACKAGES_DIRECTORY
    update              Handle updates of packages managed by pypiserver. By
                        default, a pip command to update the packages is
                        printed to stdout for introspection or pipelining. See
                        the `-x` option for updating packages directly.

optional arguments:
  -h, --help            show this help message and exit
  -v, --verbose         Enable verbose logging; repeat for more verbosity.
  --log-file FILE       Write logging info into this FILE, as well as to
                        stdout or stderr, if configured.
  --log-stream STREAM   Log messages to the specified STREAM. Valid values are
                        stdout, stderr, and none
  --log-frmt FORMAT     The logging format-string.  (see `logging.LogRecord`
                        class from standard python library)
  --hash-algo HASH_ALGO
                        Any `hashlib` available algorithm to use for
                        generating fragments on package links. Can be disabled
                        with one of (0, no, off, false).
  --backend {auto,simple-dir,cached-dir}
                        A backend implementation. Keep the default 'auto' to
                        automatically determine whether to activate caching or
                        not
  --version             show program's version number and exit

Visit https://github.com/pypiserver/pypiserver for more information
 

More details about pypi server run

Enter pypi-server run -h in the cmd-line to print a detailed usage

usage: pypi-server run [-h] [-v] [--log-file FILE] [--log-stream STREAM]
                       [--log-frmt FORMAT] [--hash-algo HASH_ALGO]
                       [--backend {auto,simple-dir,cached-dir}] [--version]
                       [-p PORT] [-i HOST] [-a AUTHENTICATE]
                       [-P PASSWORD_FILE] [--disable-fallback]
                       [--fallback-url FALLBACK_URL]
                       [--health-endpoint HEALTH_ENDPOINT] [--server METHOD]
                       [-o] [--welcome HTML_FILE] [--cache-control AGE]
                       [--log-req-frmt FORMAT] [--log-res-frmt FORMAT]
                       [--log-err-frmt FORMAT]
                       [package_directory [package_directory ...]]

positional arguments:
  package_directory     The directory from which to serve packages.

optional arguments:
  -h, --help            show this help message and exit
  -v, --verbose         Enable verbose logging; repeat for more verbosity.
  --log-file FILE       Write logging info into this FILE, as well as to
                        stdout or stderr, if configured.
  --log-stream STREAM   Log messages to the specified STREAM. Valid values are
                        stdout, stderr, and none
  --log-frmt FORMAT     The logging format-string.  (see `logging.LogRecord`
                        class from standard python library)
  --hash-algo HASH_ALGO
                        Any `hashlib` available algorithm to use for
                        generating fragments on package links. Can be disabled
                        with one of (0, no, off, false).
  --backend {auto,simple-dir,cached-dir}
                        A backend implementation. Keep the default 'auto' to
                        automatically determine whether to activate caching or
                        not
  --version             show program's version number and exit
  -p PORT, --port PORT  Listen on port PORT (default: 8080)
  -i HOST, -H HOST, --interface HOST, --host HOST
                        Listen on interface INTERFACE (default: 0.0.0.0)
  -a AUTHENTICATE, --authenticate AUTHENTICATE
                        Comma-separated list of (case-insensitive) actions to
                        authenticate (options: download, list, update;
                        default: update).
                         
                         Any actions not specified are not authenticated, so
                         to authenticate downloads and updates, but allow
                         unauthenticated viewing of the package list, you would
                         use:
                         
                          pypi-server -a 'download, update' -P
                          ./my_passwords.htaccess
                         
                        To disable authentication, use:
                         
                          pypi-server -a . -P .
                         
                        See the `-P` option for configuring users and
                        passwords.
                         
                        Note that when uploads are not protected, the
                        `register` command is not necessary, but `~/.pypirc`
                        still needs username and password fields, even if
                        bogus.
  -P PASSWORD_FILE, --passwords PASSWORD_FILE
                        Use an apache htpasswd file PASSWORD_FILE to set
                        usernames and passwords for authentication.
                         
                        To allow unauthorized access, use:
                         
                          pypi-server -a . -P .
                         
  --disable-fallback    Disable the default redirect to PyPI for packages not
                        found in the local index.
  --fallback-url FALLBACK_URL
                        Redirect to FALLBACK_URL for packages not found in the
                        local index.
  --health-endpoint HEALTH_ENDPOINT
                        Configure a custom liveness endpoint. It always
                        returns 200 Ok if the service is up. Otherwise, it
                        means that the service is not responsive.
  --server METHOD       Use METHOD to run the server. Valid values include
                        paste, cherrypy, twisted, gunicorn, gevent, wsgiref,
                        and auto. The default is to use "auto", which chooses
                        one of paste, cherrypy, twisted, or wsgiref.
  -o, --overwrite       Allow overwriting existing package files during
                        upload.
  --welcome HTML_FILE   Use the contents of HTML_FILE as a custom welcome
                        message on the home page.
  --cache-control AGE   Add "Cache-Control: max-age=AGE" header to package
                        downloads. Pip 6+ requires this for caching.AGE is
                        specified in seconds.
  --log-req-frmt FORMAT
                        A format-string selecting Http-Request properties to
                        log; set to '%s' to see them all.
  --log-res-frmt FORMAT
                        A format-string selecting Http-Response properties to
                        log; set to '%s' to see them all.
  --log-err-frmt FORMAT
                        A format-string selecting Http-Error properties to
                        log; set to '%s' to see them all.

More details about pypi-server update

More details about pypi-server update

usage: pypi-server update [-h] [-v] [--log-file FILE] [--log-stream STREAM]
                          [--log-frmt FORMAT] [--hash-algo HASH_ALGO]
                          [--backend {auto,simple-dir,cached-dir}] [--version]
                          [-x] [-d DOWNLOAD_DIRECTORY] [-u]
                          [--blacklist-file IGNORELIST_FILE]
                          [package_directory [package_directory ...]]

positional arguments:
  package_directory     The directory from which to serve packages.

optional arguments:
  -h, --help            show this help message and exit
  -v, --verbose         Enable verbose logging; repeat for more verbosity.
  --log-file FILE       Write logging info into this FILE, as well as to
                        stdout or stderr, if configured.
  --log-stream STREAM   Log messages to the specified STREAM. Valid values are
                        stdout, stderr, and none
  --log-frmt FORMAT     The logging format-string. (see `logging.LogRecord`
                        class from standard python library)
  --hash-algo HASH_ALGO
                        Any `hashlib` available algorithm to use for
                        generating fragments on package links. Can be disabled
                        with one of (0, no, off, false).
  --backend {auto,simple-dir,cached-dir}
                        A backend implementation. Keep the default 'auto' to
                        automatically determine whether to activate caching or
                        not
  --version             show program's version number and exit
  -x, --execute         Execute the pip commands rather than printing to
                        stdout
  -d DOWNLOAD_DIRECTORY, --download-directory DOWNLOAD_DIRECTORY
                        Specify a directory where packages updates will be
                        downloaded. The default behavior is to use the
                        directory which contains the package being updated.
  -u, --allow-unstable  Allow updating to unstable versions (alpha, beta, rc,
                        dev, etc.)
  --blacklist-file IGNORELIST_FILE, --ignorelist-file IGNORELIST_FILE
                        Don't update packages listed in this file (one package
                        name per line, without versions, '#' comments
                        honored). This can be useful if you upload private
                        packages into pypiserver, but also keep a mirror of
                        public packages that you regularly update. Attempting
                        to pull an update of a private package from `pypi.org`
                        might pose a security risk - e.g. a malicious user
                        might publish a higher version of the private package,
                        containing arbitrary code.


Client-Side Configurations

Always specifying the pypi url on the command line is a bit cumbersome. Since pypiserver redirects pip/easy_install to the pypi.org index if it doesn't have a requested package, it is a good idea to configure them to always use your local pypi index.

Configuring pip

For pip command this can be done by setting the environment variable PIP_EXTRA_INDEX_URL in your .bashr/.profile/.zshrc

export PIP_EXTRA_INDEX_URL=http://localhost:8080/simple/

or by adding the following lines to ~/.pip/pip.conf

[global]
extra-index-url = http://localhost:8080/simple/

Note

If you have installed pypiserver on a remote url without https you will receive an "untrusted" warning from pip, urging you to append the --trusted-host option. You can also include this option permanently in your configuration-files or environment variables.

Configuring easy_install

For easy_install command you may set the following configuration in ~/.pydistutils.cfg

[easy_install]
index_url = http://localhost:8080/simple/

Uploading Packages Remotely

Instead of copying packages directly to the server's folder (i.e. with scp), you may use python tools for the task, e.g. python setup.py upload. In that case, pypiserver is responsible for authenticating the upload-requests.

Note

We strongly advise to password-protected your uploads!

It is possible to disable authentication for uploads (e.g. in intranets). To avoid lazy security decisions, read help for -P and -a options.

Apache Like Authentication (htpasswd)

  1. First make sure you have the passlib module installed (note that passlib>=1.6 is required), which is needed for parsing the Apache htpasswd file specified by the -P, --passwords option (see next steps)
    pip install passlib
  1. Create the Apache htpasswd file with at least one user/password pair with this command (you'll be prompted for a password)
    htpasswd -sc htpasswd.txt <some_username>

Tip

Read this SO question for running htpasswd cmd under Windows or if you have bogus passwords that you don't care because they are for an internal service (which is still "bad", from a security perspective...) you may use this public service

Tip

When accessing pypiserver via the api, alternate authentication methods are available via the auther config flag. Any callable returning a boolean can be passed through to the pypiserver config in order to provide custom authentication. For example, to configure pypiserver to authenticate using the python-pam

    import pam
    pypiserver.default_config(auther=pam.authenticate)

Please see Using Ad-hoc authentication providers_ for more information.

  1. You need to restart the server with the -P option only once (but user/password pairs can later be added or updated on the fly)
    ./pypi-server run -p 8080 -P htpasswd.txt ~/packages &

Upload with setuptools

  1. On client-side, edit or create a ~/.pypirc file with a similar content:
     [distutils]
     index-servers =
       pypi
       local

     [pypi]
     username:<your_pypi_username>
     password:<your_pypi_passwd>

     [local]
     repository: http://localhost:8080
     username: <some_username>
     password: <some_passwd>
  1. Then from within the directory of the python-project you wish to upload, issue this command:
     python setup.py sdist upload -r local

Upload with twine

To avoid storing you passwords on disk, in clear text, you may either:

  • use the register setuptools's command with the -r option, like that
  python setup.py sdist register -r local upload -r local
  • use twine library, which breaks the procedure in two steps. In addition, it supports signing your files with PGP-Signatures and uploading the generated .asc files to pypiserver::
  twine upload -r local --sign -identity user_name ./foo-1.zip

Using the Docker Image

Starting with version 1.2.5, official Docker images will be built for each push to master, each dev, alpha, or beta release, and each final release. The most recent full release will always be available under the tag latest, and the current master branch will always be available under the tag unstable.

You can always check to see what tags are currently available at our Docker Repo.

To run the most recent release of pypiserver with Docker, simply

    docker run pypiserver/pypiserver:latest run

This starts pypiserver serving packages from the /data/packages directory inside the container, listening on the container port 8080.

The container takes all the same arguments as the normal pypi-server executable, with the exception of the internal container port (-p), which will always be 8080.

Of course, just running a container isn't that interesting. To map port 80 on the host to port 8080 on the container::

    docker run -p 80:8080 pypiserver/pypiserver:latest run

You can now access your pypiserver at localhost:80 in a web browser.

To serve packages from a directory on the host, e.g. ~/packages

    docker run -p 80:8080 -v ~/packages:/data/packages pypiserver/pypiserver:latest run

To authenticate against a local .htpasswd file::

    docker run -p 80:8080 -v ~/.htpasswd:/data/.htpasswd pypiserver/pypiserver:latest run -P .htpasswd packages

You can also specify pypiserver to run as a Docker service using a composefile. An example composefile is provided

Alternative Installation Methods

When trying the methods below, first use the following command to check whether previous versions of pypiserver already exist, and (optionally) uninstall them::

# VERSION-CHECK: Fails if not installed.
pypi-server --version

# UNINSTALL: Invoke again until it fails.
pip uninstall pypiserver

Installing the Very Latest Version

In case the latest version in pypi is a pre-release, you have to use pip's --pre option. And to update an existing installation combine it with --ignore-installed

pip install pypiserver --pre -I

You can even install the latest pypiserver directly from github with the following command, assuming you have git installed on your PATH

pip install git+git://github.com/pypiserver/pypiserver.git

Recipes

Managing the Package Directory

The pypi-server command has the update command that searches for updates of available packages. It scans the package directory for available packages and searches on pypi.org for updates. Without further options pypi-server update will just print a list of commands which must be run in order to get the latest version of each package. Output looks like

    $ ./pypi-server update 
    checking 106 packages for newer version

    .........u.e...........e..u.............
    .....e..............................e...
    ..........................

    no releases found on pypi for PyXML, Pymacs, mercurial, setuptools

    # update raven from 1.4.3 to 1.4.4
    pip -q install --no-deps  --extra-index-url https://pypi.org/simple/ -d /home/ralf/packages/mirror raven==1.4.4

    # update greenlet from 0.3.3 to 0.3.4
    pip -q install --no-deps  --extra-index-url https://pypi.org/simple/ -d /home/ralf/packages/mirror greenlet==0.3.4

It first prints for each package a single character after checking the available versions on pypi. A dot(.) means the package is up-to-date, 'u' means the package can be updated and 'e' means the list of releases on pypi is empty. After that it shows a pip command line which can be used to update a one package. Either copy and paste that or run pypi-server update -x in order to really execute those commands. You need to have pip installed for that to work however.

Specifying an additional -u option will also allow alpha, beta and release candidates to be downloaded. Without this option these releases won't be considered.

Serving Thousands of Packages

By default, pypiserver scans the entire packages directory each time an incoming HTTP request occurs. This isn't a problem for a small number of packages, but causes noticeable slow-downs when serving thousands of packages.

If you run into this problem, significant speedups can be gained by enabling pypiserver's directory caching functionality. The only requirement is to install the watchdog package, or it can be installed during pypiserver installation, by specifying the cache extras option::

    pip install pypiserver[cache]

Additional speedups can be obtained by using your webserver's builtin caching functionality. For example, if you are using nginx as a reverse-proxy as described below in Behind a reverse proxy, you can easily enable caching. For example, to allow nginx to cache up to 10 gigabytes of data for up to 1 hour::

    proxy_cache_path /data/nginx/cache
                     levels=1:2
                     keys_zone=pypiserver_cache:10m
                     max_size=10g
                     inactive=60m
                     use_temp_path=off;

    server {
        # ...
        location / {
            proxy_cache pypiserver_cache;
            proxy_pass http://localhost:8080;
        }
    }

Using webserver caching is especially helpful if you have high request volume. Using nginx caching, a real-world pypiserver installation was able to easily support over 1000 package downloads/min at peak load.

Managing Automated Startup

There are a variety of options for handling the automated starting of pypiserver upon system startup. Two of the most common are systemd and supervisor for linux systems. For windows creating services with scripts isn't an easy task without a third party tool such as NSSM.

Running As a systemd Service

systemd is installed by default on most modern Linux systems and as such, it is an excellent option for managing the pypiserver process. An example config file for systemd can be seen below

    [Unit]
    Description=A minimal PyPI server for use with pip/easy_install.
    After=network.target

    [Service]
    Type=simple
    # systemd requires absolute path here too.
    PIDFile=/var/run/pypiserver.pid
    User=www-data
    Group=www-data

    ExecStart=/usr/local/bin/pypi-server run -p 8080 -a update,download --log-file /var/log/pypiserver.log -P /etc/nginx/.htpasswd /var/www/pypi
    ExecStop=/bin/kill -TERM $MAINPID
    ExecReload=/bin/kill -HUP $MAINPID
    Restart=always

    WorkingDirectory=/var/www/pypi

    TimeoutStartSec=3
    RestartSec=5

    [Install]
    WantedBy=multi-user.target

Adjusting the paths and adding this file as pypiserver.service into your systemd/system directory will allow management of the pypiserver process with systemctl, e.g. systemctl start pypiserver.

More useful information about systemd can be found at https://www.digitalocean.com/community/tutorials/how-to-use-systemctl-to-manage-systemd-services-and-units

Launching through supervisor

supervisor has the benefit of being a pure python package and as such, it provides excellent cross-platform support for process management. An example configuration file for supervisor is given below

    [program:pypi]
    command=/home/pypi/pypi-venv/bin/pypi-server run -p 7001 -P /home/pypi/.htpasswd /home/pypi/packages
    directory=/home/pypi
    user=pypi
    autostart=true
    autorestart=true
    stderr_logfile=/var/log/pypiserver.err.log
    stdout_logfile=/var/log/pypiserver.out.log

From there, the process can be managed via supervisord using supervisorctl.

Running As a service with NSSM

For Windows download NSSM from https://nssm.cc unzip to a desired location such as Program Files. Decide whether you are going to use win32 or win64, and add that exe to environment PATH.

Create a start_pypiserver.bat

    pypi-server run -p 8080 C:\Path\To\Packages &

Test the batch file by running it first before creating the service. Make sure you can access the server remotely, and install packages. If you can, proceed, if not troubleshoot until you can. This will ensure you know the server works, before adding NSSM into the mix.

From the command prompt

    nssm install pypiserver

This command will launch a NSSM gui application

    Path: C:\Path\To\start_pypiserver.bat
    Startup directory: Auto generates when selecting path
    Service name: pypiserver

There are more tabs, but that is the basic setup. If the service needs to be running with a certain login credentials, make sure you enter those credentials in the logon tab.

Start the service

    nssm start pypiserver

Other useful commands

    nssm --help
    nssm stop <servicename>
    nssm restart <servicename>
    nssm status <servicename>

For detailed information please visit https://nssm.cc

Using a Different WSGI Server

  • The bottle web-server which supports many WSGI-servers, among others, paste, cherrypy, twisted and wsgiref (part of Python); you select them using the --server flag.

  • You may view all supported WSGI servers using the following interactive code

    >>> from pypiserver import bottle
    >>> list(bottle.server_names.keys())
    ['cgi', 'gunicorn', 'cherrypy', 'eventlet', 'tornado', 'geventSocketIO',
   'rocket', 'diesel', 'twisted', 'wsgiref', 'fapws3', 'bjoern', 'gevent',
   'meinheld', 'auto', 'aiohttp', 'flup', 'gae', 'paste', 'waitress']
  • If none of the above servers matches your needs, invoke just the pypiserver:app() method which returns the internal WSGI-app WITHOUT starting-up a server - you may then send it to any WSGI server you like. Read also the Utilizing the API section.

  • Some examples are given below - you may find more details in bottle site.

Apache

To use your Apache2 with pypiserver, prefer to utilize mod_wsgi as explained in bottle's documentation.

Note If you choose instead to go with mod_proxy, mind that you may bump into problems with the prefix-path (see #155).

  1. Adapt and place the following Apache configuration either into top-level scope, or inside some (contributed by Thomas Waldmann):
        WSGIScriptAlias   /     /yoursite/wsgi/pypiserver-wsgi.py
        WSGIDaemonProcess       pypisrv user=pypisrv group=pypisrv umask=0007 \
                                processes=1 threads=5 maximum-requests=500 \
                                display-name=wsgi-pypisrv inactivity-timeout=300
        WSGIProcessGroup        pypisrv
        WSGIPassAuthorization On    # Required for authentication (https://github.com/pypiserver/pypiserver/issues/288)

        <Directory /yoursite/wsgi >
            Require all granted
        </Directory>

or if using older Apache < 2.4, substitute the last part with this::

        <Directory /yoursite/wsgi >
            Order deny,allow
            Allow from all
        </Directory>
  1. Then create the /yoursite/cfg/pypiserver.wsgi file and make sure that the user and group of the WSGIDaemonProcess directive (pypisrv:pypisrv in the example) have the read permission on it
        import pypiserver

        conf = pypiserver.default_config(
            root =          "/yoursite/packages",
            password_file = "/yoursite/htpasswd", )
        application = pypiserver.app(**conf)

Tip If you have installed pypiserver in a virtualenv, follow mod_wsgi's instructions and prepend the python code above with the following

    import site

    site.addsitedir('/yoursite/venv/lib/pythonX.X/site-packages')

Note For security reasons, notice that the Directory directive grants access to a directory holding the wsgi start-up script, alone; nothing else.

Note To enable HTTPS support on Apache, configure the directive that contains the WSGI configuration to use SSL.

gunicorn

The following command uses gunicorn to start pypiserver

  gunicorn -w4 'pypiserver:app(root="/home/ralf/packages")'

or when using multiple roots

  gunicorn -w4 'pypiserver:app(root=["/home/ralf/packages", "/home/ralf/experimental"])'

paste

paste allows to run multiple WSGI applications under different URL paths. Therefore, it is possible to serve different set of packages on different paths.

The following example paste.ini could be used to serve stable and unstable packages on different paths

    [composite:main]
    use = egg:Paste#urlmap
    /unstable/ = unstable
    / = stable

    [app:stable]
    use = egg:pypiserver#main
    root = ~/stable-packages

    [app:unstable]
    use = egg:pypiserver#main
    root = ~/stable-packages
       ~/unstable-packages

    [server:main]
    use = egg:gunicorn#main
    host = 0.0.0.0
    port = 9000
    workers = 5
    accesslog = -

Note You need to install some more dependencies for this to work, like::

  pip install paste pastedeploy gunicorn pypiserver

The server can then start with

  gunicorn_paster paste.ini

Behind a Reverse Proxy

You can run pypiserver behind a reverse proxy as well.

Nginx

Extend your nginx configuration

    upstream pypi {
      server              pypiserver.example.com:12345 fail_timeout=0;
    }

    server {
      server_name         myproxy.example.com;

      location / {
        proxy_set_header  Host $host:$server_port;
        proxy_set_header  X-Forwarded-Proto $scheme;
        proxy_set_header  X-Real-IP $remote_addr;
        proxy_pass        http://pypi;
      }
    }

As of pypiserver 1.3, you may also use the X-Forwarded-Host header in your reverse proxy config to enable changing the base URL. For example if you want to host pypiserver under a particular path on your server

    upstream pypi {
      server              localhost:8000;
    }

    server {
      location /pypi/ {
          proxy_set_header  X-Forwarded-Host $host:$server_port/pypi;
          proxy_set_header  X-Forwarded-Proto $scheme;
          proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header  X-Real-IP $remote_addr;
          proxy_pass        http://pypi;
      }
    }

Supporting HTTPS

Using a reverse proxy is the preferred way of getting pypiserver behind HTTPS. For example, to put pypiserver behind HTTPS on port 443, with automatic HTTP redirection, using nginx

    upstream pypi {
      server               localhost:8000;
    }

    server {
      listen              80 default_server;
      server_name         _;
      return              301 https://$host$request_uri;
    }

    server {
      listen              443 ssl;
      server_name         pypiserver.example.com;

      ssl_certificate     /etc/star.example.com.crt;
      ssl_certificate_key /etc/star.example.com.key;
      ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
      ssl_ciphers         HIGH:!aNULL:!MD5;

      location / {
        proxy_set_header  Host $host:$server_port;
        proxy_set_header  X-Forwarded-Proto $scheme;
        proxy_set_header  X-Real-IP $remote_addr;
        proxy_pass        http://pypi;
      }
    }

Please see nginx's HTTPS docs for more details.

Getting and keeping your certificates up-to-date can be simplified using, for example, using certbot and letsencrypt.

Traefik

It is also possible to use Traefik to put pypiserver behind HTTPS on port 443, with automatic HTTP redirection using Docker Compose. Please see the provided docker-compose.yml example for more information.

Utilizing the API

In order to enable ad-hoc authentication-providers or to use WSGI-servers not supported by bottle out-of-the-box, you needed to launch pypiserver via its API.

  • The main entry-point for configuring pypiserver is the pypiserver:app() function. This function returns the internal WSGI-app that you my then send to any WSGI-server you like.

  • To get all pypiserver:app() keywords and their explanations, read the function pypiserver:default_config()

  • Finally, to fire-up a WSGI-server with the configured app, invoke the bottle:run(app, host, port, server) function. Note that pypiserver ships with its own copy of bottle; to use it, import it like that: from pypiserver import bottle

Using Ad-Hoc Authentication Providers

The auther keyword of pypiserver:app() function maybe set only using the API. This can be any callable that returns a boolean when passed the username and the password for a given request.

For example, to authenticate users based on the /etc/passwd file under Unix, you may delegate such decisions to the python-pam library by following these steps:

  1. Ensure python-pam module is installed

    pip install python-pam

  2. Create a python-script along these lines

   $ cat > pypiserver-start.py
   import pypiserver
   from pypiserver import bottle
   import pam
   app = pypiserver.app(root='./packages', auther=pam.authenticate)
   bottle.run(app=app, host='0.0.0.0', port=80, server='auto')

   [Ctrl+ D]
  1. Invoke the python-script to start-up pypiserver
   python pypiserver-start.py

Note The python-pam module, requires read access to /etc/shadow file; you may add the user under which pypiserver runs into the shadow group, with a command like this: sudo usermod -a -G shadow pypy-user.

Use with MicroPython

The MicroPython interpreter for embedded devices can install packages with the module upip.py. The module uses a specialized json-endpoint to retrieve package information. This endpoint is supported by pypiserver.

It can be tested with the UNIX port of micropython

    cd micropython
    ports/unix/micropython -m tools.upip install -i http://my-server:8080 -p /tmp/mymodules micropython-foobar

Installing packages from the REPL of an embedded device works in this way:

    import network
    import upip

    sta_if = network.WLAN(network.STA_IF)
    sta_if.active(True)
    sta_if.connect('<your ESSID>', '<your password>')
    upip.index_urls = ["http://my-server:8080"]
    upip.install("micropython-foobar")

Further information on micropython-packaging can be found here: https://docs.micropython.org/en/latest/reference/packages.html

Custom Health Check Endpoint

pypiserver provides a default health endpoint at /health. It always returns 200 Ok if the service is up. Otherwise, it means that the service is not responsive.

In addition, pypiserver allows users to customize the health endpoint. Alphanumeric characters, hyphens, forward slashes and underscores are allowed and the endpoint should not overlap with any existing routes. Valid examples: /healthz, /health/live-1, /api_health, /action/health

Configure a custom health endpoint by CLI arguments

Run pypiserver with --health-endpoint argument:

    pypi-server run --health-endpoint /action/health

Configure a custom health endpoint by script

    import pypiserver
    from pypiserver import bottle
    app = pypiserver.app(root="./packages", health_endpoint="/action/health")
    bottle.run(app=app, host="

```python
    import pypiserver
    from pypiserver import bottle
    app = pypiserver.app(root="./packages", health_endpoint="/action/health")
    bottle.run(app=app, host="0.0.0.0", port=8080, server="auto")

Try curl http://localhost:8080/action/health

Sources

To create a copy of the repository, use

    git clone https://github.com/pypiserver/pypiserver.git
    cd pypiserver

To receive any later changes, in the above folder use:

    git pull

Known Limitations

pypiserver does not implement the full API as seen on PyPI. It implements just enough to make easy_install, pip install, and search work.

The following limitations are known:

  • Command pypi -U that compares uploaded packages with pypi to see if they are outdated, does not respect a http-proxy environment variable (see #19.
  • It accepts documentation uploads but does not save them to disk (see #47 for a discussion)
  • It does not handle misspelled packages as pypi-repo does, therefore it is suggested to use it with --extra-index-url instead of --index-url (see #38).

Please use Github's bugtracker for other bugs you find.

Similar Projects

There are lots of other projects, which allow you to run your own PyPI server. If pypiserver doesn't work for you, the following are among the most popular alternatives:

Unmaintained or archived

These projects were once alternatives to pypiserver but are now either unmaintained or archived.

  • pip2pi a simple cmd-line tool that builds a PyPI-compatible local folder from pip requirements

  • flask-pypi-proxy A proxy for PyPI that also enables uploading custom packages.

Related Software

Though not direct alternatives for pypiserver's use as an index server, the following is a list of related software projects that you may want to familiarize with:

  • pypi-uploader: A command-line utility to upload packages to your pypiserver from pypi without having to store them locally first.

  • twine: A command-line utility for interacting with PyPI or pypiserver.

  • warehouse: the software that powers PyPI itself. It is not generally intended to be run by end-users.

Licensing

pypiserver contains a copy of bottle which is available under the MIT license, and the remaining part is distributed under the zlib/libpng license. See the LICENSE.txt file.

pypiserver's People

Contributors

alexandrul avatar ankostis avatar cclauss avatar corywright avatar dee-me-tree-or-love avatar dependabot[bot] avatar dpkp avatar elboerto avatar elfjes avatar geryogam avatar ghinks avatar github-actions[bot] avatar hugovk avatar jayeff avatar khornberg avatar kujyp avatar lowks avatar luismsgomes avatar mason-lin avatar mplanchard avatar ngnpope avatar oneplus avatar petri avatar ror6ax avatar sakurai-youhei avatar saltycrane avatar schmir avatar sposs avatar virtuald avatar vsajip avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pypiserver's Issues

Caching from upstream server

pypiserver-1.0 supports a fallbackurl fine. A few questions:

  • if the package query which is redirect to pypi.python.org has dependencies will pip/easy_install again first ask the initial instance (pypiserver-1.0)?
  • did you consider performing the query to pypi.python.org yourself and caching the result so that on the next occassion the server will know about it (after all, releases/files can be thought as immutable usually)?

build_ext on mirror?

I asked on stackoverlfow, but nobody replied. Here is the question again:

http://stackoverflow.com/questions/17275323/pypiserver-build-ext-on-mirror

We have a local pypiserver and up to now we are happy with it.

But psycopg2 makes trouble. It wants pg_config to be installed. I don't see a reason why it should be installed on the mirror server. I understand that it needs to be on the client where I install psycopg2.

Is this a bug in psycopg2? Or do I use the wrong options the get the package to the mirror?

pypi@gray:~> pip install --no-deps --no-install -d packages psycopg2
Downloading/unpacking psycopg2
File was already downloaded packages/psycopg2-2.5.1.tar.gz
Running setup.py egg_info for package psycopg2
Error: pg_config executable not found.

Please add the directory containing pg_config to the PATH
or specify the full executable path with the option:

    python setup.py build_ext --pg-config /path/to/pg_config build ...

or with the pg_config option in 'setup.cfg'.
Complete output from command python setup.py egg_info:
running egg_info

creating pip-egg-info/psycopg2.egg-info

writing pip-egg-info/psycopg2.egg-info/PKG-INFO

writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt

writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt

writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt'

warning: manifest_maker: standard file '-c' not found

Error: pg_config executable not found.

Please add the directory containing pg_config to the PATH

or specify the full executable path with the option:

python setup.py build_ext --pg-config /path/to/pg_config build ...

or with the pg_config option in 'setup.cfg'.


Command python setup.py egg_info failed with error code 1 in /home/pypi/tmp/pip-build/psycopg2
Storing complete log in /home/pypi/.config/pip/pip.log

We use this pypiserver: https://pypi.python.org/pypi/pypiserver

Creted the local pypiserver but not able to upload package to my local pypiserver

http://pypi.python.org/pypi/pypiserver/#table-of-contents
Fallowed the all the stepps mentioned in above link.
But when i am going to upload package to my local pypi server.

  1. python setup.py sdist upload -r internal

`When i ran above command by default it's going to pypi.python.org server '

removing 'boto-2.8.0' (and everything under it)
running upload
Submitting dist/boto-2.8.0.tar.gz to http://pypi.python.org/pypi
Upload failed (401): You must be identified to edit package information.

  1. python setup.py sdist upload -r http://localhost:7080/simple

When i ran above command getting below issue.
running upload
Submitting dist/boto-2.8.0.tar.gz to http://localhost:7080/simple
[Errno 32] Broken pipe

Can any one suggest how to upload package to local pypi server.

pip install pypiserver fails with 404

$ pip install pypiserver --upgrade
Downloading/unpacking pypiserver
HTTP error 404 while getting http://pypi.python.org/packages/source/p/pypiserver/pypiserver-0.4.0.zip#md5=1a1a30d75b92137e99e7bf967a98d3e9 (from http://pypi.python.org/simple/pypiserver/)
Could not install requirement pypiserver because of error HTTP Error 404: Not Found ()
Could not install requirement pypiserver because of HTTP error HTTP Error 404: Not Found () for URL http://pypi.python.org/packages/source/p/pypiserver/pypiserver-0.4.0.zip#md5=1a1a30d75b92137e99e7bf967a98d3e9 (from http://pypi.python.org/simple/pypiserver/)

Going to http://pypi.python.org/pypi/pypiserver/#downloads in my browser and attempting to download the 0.4 source tarball also results in a 404.

Provide hash in the link for local packages

pip 1.5 and greater would like secure links by default, which by implementation means the link provides a hash of the package in the url. This provides some form of verification of correct file download at least.

You can see some of the api docs at warehouse how this is done.

It would be great for pypiserver's links to provide this for pip; I believe this would mean you no longer have to pass --allow-insecure.

bottle BaseRequest.MAX_PARAMS causes HTTPError: 400 Client Error: Bad Request on packages with more than 100 requirements.

Hi.
Geez, this was a nightmare to track down ;).
Look at BaseRequest.MAX_PARAMS

We have a package with 112 requirements at the company, this caused HTTPError: 400 Client Error: Bad Request as this exceeded allowed POST parameters.

You can reproduce by building this fake package and uploading it (I used twine):

from setuptools import setup
setup(
    name='pyserver_test',
    install_requires=['a==1.0'] * 200,
)
$ pip wheel .
$ twine upload -r my_locally_run_pypiserver wheelhouse/pyserver_test-0.0.0-cp27-none-linux_x86_64.whl 
Uploading distributions to http://127.0.0.1:8080
Uploading pyserver_test-0.0.0-cp27-none-linux_x86_64.whl
HTTPError: 400 Client Error: Bad Request

Please explain why cap at 100 (I assume this is a question to bottle authors). I can easily fix this in my fork but I don't have an idea how to elegantly fix it for everyone else.

Does not work in Windows?

I've set up pypiserver 1.1.6 on Windows7 using python 2.7.9 and pip 6.0.8.

http://localhost:8080/simple/ lists my package without problems but
pip install -i http://localhost:8080/simple pygrids says:

Collecting pygrids
  DEPRECATION: Failed to find 'pygrids' at http://localhost:8080/simple/pygrids/. It is suggested to upgrade your index to support
 normalized names as the name in /simple/{name}.
  Cannot fetch index base URL http://localhost:8080/simple/
  Could not find any downloads that satisfy the requirement pygrids
  No distributions at all found for pygrids

The different version of the pygrids package are:

pygrids-0.1.tar.gz
pygrids-0.2.tar.gz
pygrids-0.2.1.tar.gz

Same setup works on Ubuntu 14.04

Add caching for the fallback URL packages

  1. Add option --fallback-cache-root or -c
  2. If the package is not found locally
    1. Search fallback cache root
    2. If fallback cache root doesn't have the package
      1. Retrieve the package
      2. Store it in the fallback root
      3. Send it to the requesting client
    3. If fallback cache root does have the package
      1. Check whether package is older than --cache-control and if older proceed to 2.ii.a
      2. Otherwise send the cached package to the requesting client

support for setup.py register command is broken

I have fresh pypiserver 1.1.7 running on current Debian Stable, on Python2.7.

For some reason, running "python setup.py sdist register upload" works, but just "setup.py register" does not (locally):

Server response (500): <urlopen error [Errno 104] Connection reset by peer>

Or from a remote OSX system:

Server response (500): <urlopen error [Errno 32] Broken pipe>

... and likewise, using jarn.mkrelease (tool to automate releases) from the OSX system to do uploads fails:
(it does register - sdist - upload in three separate HTTP calls, I guess)

running register
Registering z3c.form to http://pypi.vidamin.com:8765
Server response (500): <urlopen error [Errno 32] Broken pipe>
ERROR: register failed

In all these cases, the pypiserver log shows just:

"POST / HTTP/1.1" 401 713 "-" "Python-urllib/2.7"

Which is not very helpful...

pypiserver should accept the register call on its own, even if just to satisfy clients (and users) that try to do "setup.py register" on its own without other commands. My suggestion would be to simply silently accept the call, and do nothing (except log the event perhaps).

Note: I suspect this issue may be behind a few other issue reports about "random" 401 or 500 errors, as well... I thought for a long time I was seeing the same issue.

At the very least, it should be documented that doing just "setup.py register" does not work.

Pypi server randomly sends 401 error on upload

When I try to upload my pip's to the pypiser server, it will fail with a 401 error a random amount of times, then magically be accepted. This goes for registering the package as well. The logging is not very helpful in figuring out what exactly has gone wrong.

Here is logging output:

[09/Jul/2012:13:46:00 +0000] "POST / HTTP/1.1" 401 729 "-" "Python-urllib/2.7"
[09/Jul/2012:13:46:01 +0000] "POST / HTTP/1.1" 401 729 "-" "Python-urllib/2.7"
[09/Jul/2012:13:46:01 +0000] "POST / HTTP/1.1" 200 0 "-" "Python-urllib/2.7"
[09/Jul/2012:13:46:19 +0000] "POST / HTTP/1.1" 200 0 "-" "Python-urllib/2.7"

conflicting filenames "tip.zip" for dev versions

For moin2, we need flatland==dev. if one downloads that with the suggested pip command, it gets stored as tip.zip into the package mirror directory.

if i add another package with ==dev, that one gets also stored as tip.zip.

This obviously can't work. Is there a way to handle this?

Aside from the conflict, it also loses information about what package that was. I suspect when looking for updates pypi-server will only look at the filenames in the package mirror directory and it won't know from which package name that tip.zip came from.

Bottle missing gevent monkey patch

Currently, attempting to run pypiserver with --server gevent fails due to lack of a monkey patch call:

$ pip freeze | grep pypiserver
pypiserver==1.1.6
$ pip freeze | grep gevent
gevent==1.0
$ pypi-server --server gevent -P htpasswd goat/
This is pypiserver 1.1.6 serving '/home/vagrant/goat' on http://0.0.0.0:8080

Bottle v0.11.6 server starting up (using GeventServer())...
Listening on http://0.0.0.0:8080/
Hit Ctrl-C to quit.

Traceback (most recent call last):
  File "/home/vagrant/.env/bin/pypi-server", line 11, in <module>
    sys.exit(main())
  File "/home/vagrant/.env/local/lib/python2.7/site-packages/pypiserver/core.py", line 328, in main
    run(app=a, host=host, port=port, server=server)
  File "/home/vagrant/.env/local/lib/python2.7/site-packages/pypiserver/bottle.py", line 2703, in run
    server.run(app)
  File "/home/vagrant/.env/local/lib/python2.7/site-packages/pypiserver/bottle.py", line 2499, in run
    raise RuntimeError(msg)
RuntimeError: Bottle requires gevent.monkey.patch_all() (before import)

'module' object has no attribute 'spawnlp'

Windows support seems to be broken due to the usage of os.spawnlp:

http://docs.python.org/2/library/os.html#os.spawnlp:

# update Django from 1.4.1 to 1.4.3
pip -q install --no-deps -i http://pypi.python.org/simple -d D:\hackable-pypi\_data Django==1.4.3

Traceback (most recent call last):
  File "D:\hackable-pypi\python\Scripts\pypi-server-script.py", line 9, in <module>
    load_entry_point('pypiserver==1.0.0', 'console_scripts', 'pypi-server')()
  File "d:\hackable-pypi\pypiserver\pypiserver\core.py", line 255, in main
    manage.update(packages, update_directory, update_dry_run, stable_only=update_stable_only)
  File "d:\hackable-pypi\pypiserver\pypiserver\manage.py", line 137, in update
    os.spawnlp(os.P_WAIT, cmd[0], *cmd)
AttributeError: 'module' object has no attribute 'spawnlp'

document how to initialize the wsgi app

I just had a quick glance over the docs, but I could not find how to use pypiserver as a wsgi app.

It looks like it is using wsgi internally, but usually one would expect there is a documented way to initialize the wsgi app and use it with ANY wsgi server one likes, not just the ones supported by bottle. Isn't that why wsgi was implemented in the first place?

For apache2 / mod_wsgi users, a pypiserver.wsgi would also be a nice addition.

Pip install requires <package_name>==<version>

My package is uploaded and I can see it when I browse http://server/simple

When running pip install I get the message: "Could not find a version that satisfies the requirement <package_name> (from versions: 1.0.0d5, 1.0.0d7)"

pip install <package_name>==<version> works, but I would like it to auto-negotiate the latest version.

Am I doing something incorrectly, or does pypiserver not support my type of versioning? If so, could you point me at the relevant code?

Non-numeric version values are assumed to be part of package name

Maybe this is the wrong way to handle this problem, but according to git flow, the develop branch of a project should not have any version number (how can you know what version you're going to release until you're in the release tagging stage?, or so the argument goes).

My version number is, therefore, "DEVELOP". This creates packages that look like this: "foo-DEVELOP-1402948847.tar.gz".

It looks like the "DEVELOP" part of this package filename is being included as part of the package name in the default "/simple" view.

I'm not really even sure if this is an actual bug, but I wanted to mention it, and see if there was anything that could be done. In the meantime my intended workaround is to slip in a numeric value before "DEVELOP", which I think will cause it to be considered the remaining text to be a "version" identifier.

Adding /simple/ to dependency_links?

I set up a pypi server with some packages and tried adding the /simple/ URL to one of the packages setup.py script's dependency_links. When I run pip install or easy_install it fails to find the package at /simple/. When I add a package name to the path in dependency_links it does work. Can this work without having to add explicit paths for each dependency? I want to avoid having to tell users to configure pip or easy_install to pull from our server.

docs say no upload is possible but 1.0 supports it

I managed to create a htpasswd file and use register/upload with pypiserver-1.0. The docs don't really discuss this feature and also the comparison with other pypi servers seems to be based on an earlier release (otherwise why highlight that others have upload).

pypiserver needs a new maintainer

I don't use python anymore and won't support pypiserver anymore. Someone else should take over.

Please take a look at devpi for a well maintained alternative.

Copyright dates are outdated

Harsh Gupta [email protected] points out in email to webmaster@ that the page footer still shows "Copyright © 1990-2014, Python Software Foundation." The easy fix is a change to the templates, but it might be better to simply dynamically substitute the current year for the second date.

Release v1.1.7

@schmir, @ror6ax and @dingus9:
I believe it is time to make the 1st public release under the new ownership scheme.

  • The PR's marked for inclusion are marked with milestone=v1.1.7.
  • I'm hopping to start merging during the weekend.
  • Arbitrarily set release-date on 25-January.
  • @schmir i will need you to give access to my pypi-account (named also ankostis) for uploading released packages.
  • @dingus9 you have to add yourself into the watchers of this project (it is not done automatically).

1.1.7 and random 503

I tried both with the default bottle webserver and gunicorn (-w4) and every now and then I get a 503 making the mirror unreliable.

I am digging into the code to find more clues.

Refuses to use local server

Running this, I still get results when I take the local server down:

$ PIP_INDEX_URL=https://pypi.local/simple pip -v search gdrivefs

The -v option is supposed to turn-on verbosity, but there's nothing.

implement package upload

Thanks for pypiserver. I must say it is the most stable and clean pypi alternative implementations out there for now tho, it's still feature incomplete.

Please do consider allowing package upload by using python setup.py upload as it is the most convenient way to to distribute a private package.

Cross Site Scripting Vulnerability

Versions up to and including 1.1.7 contain a cross site scripting vulnerability. I acknowledge this is not likely to ever be a problem since the normal usage of the server is from pip rather than a web browser. I only note it because my server was flagged as vulnerable by a Nessus scan.

The vulnerability can be demonstrated by entering the following in a web browser that does not filter XSS (on modern browsers, you'll probably have to disable automatic XSS filtering to see the exploit)
http://my.pypi-server.com:8080/?<script>alert("Vulnerable!");</script>

If successful, this should pop up an alert window,

support voor virtual hosts

I have pypiserver running on apache/mod_wsgi, served under "/pypi"

but the some links on the homepage are incorrect
because they don not take into account request.fullpath

in
58 @app.route('/')
59 def root():

"packages" point to "/packages" instead of "/pypi/packages"
"simple" point to "/packages" instead of "/pypi/simple"

--log-file not working in 1.1.7

I'm confused, or there is a bug.

I'm using --log-file with a pathname and nothing is being written there.

The server is acting as it always has and logs to stdout + stderr instead of to my specified log file.

The process, showing --log-file /var/log/pypiserver.log as the place to log.

pypi     16729 16728  0 15:52 ?        00:00:00 /apps/pypi-server/bin/python /apps/pypi-server/bin/pypi-server -p 8080 -P /apps/htaccess-live --log-file /var/log/pypiserver.log /apps/pypi-server-data

And the files:

Exhibit A: The 0-length log file that I primed and chown()ed before starting the process.

Exhibit B: The pypi-stdout-stderr.log file that is being captured from my boot-time script. It grows as HTTP requests come in and contains log lines.

log:pypi# cd /var/log
log:pypi# ls -lart
...
-rw-------   1 pypi root        0 Mar 13 15:49 pypiserver.log            <--- A
drwxr-xr-x. 14 root root     4096 Mar 13 15:58 .
-rw-------   1 root root      755 Mar 13 15:58 pypi-stdout-stderr.log   <--- B
log:pypi# cat pypi-stdout-stderr.log
Bottle v0.11.6 server starting up (using AutoServer())...
Listening on http://0.0.0.0:8080/
Hit Ctrl-C to quit.

/apps/pypi-server/lib/python2.6/site-packages/pypiserver/_app.py:174: DeprecationWarning: The COOKIES dict is deprecated. Use `set_cookie()` instead.
  body=response.body, cookies=response.COOKIES,
jblaine.our.org - - [13/Mar/2015 15:58:12] "GET / HTTP/1.1" 200 809
jblaine.our.org - - [13/Mar/2015 15:58:14] "GET / HTTP/1.1" 200 809
jblaine.our.org - - [13/Mar/2015 15:58:15] "GET / HTTP/1.1" 200 809
log:pypi#

Valid package names are stored incorrectly with new version of bottle

Not sure when this was introduced, but pypiserver 1.1.2 didn't have this issue. From the bottle API docs:

Name of the file on the client file system, but normalized to ensure file system compatibility. An empty filename is returned as ‘empty’. Only ASCII letters, digits, dashes, underscores and dots are allowed in the final filename. Accents are removed, if possible. Whitespace is replaced by a single dash. Leading or tailing dots or dashes are removed. The filename is limited to 255 characters.

For example, the version 0.0.0+local is a valid package version, but bottle gets rid of the +. I'm sure there are other combinations that also break.

Example commands in docs mention `.htaccess`, while implying `.htpasswd`

When starting the pypi-server I get an error message saying "malformed htpasswd file". I get the error message even if the .htpasswd file does not exist. What is causing the error?

Here is the entire Traceback:

C:\Data>pypi-server -p 8080 -P packages\.htaccess packages
Traceback (most recent call last):
  File "c:\python27\lib\runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "c:\python27\lib\runpy.py", line 72, in _run_code
    exec code in run_globals
  File "C:\Python27\Scripts\pypi-server.exe\__main__.py", line 9, in <module>
  File "c:\python27\lib\site-packages\pypiserver\__main__.py", line 293, in main
    app = pypiserver.app(**vars(c))
  File "c:\python27\lib\site-packages\pypiserver\__init__.py", line 124, in app
    config, packages = core.configure(**kwds)
  File "c:\python27\lib\site-packages\pypiserver\core.py", line 47, in configure
    htPsswdFile = HtpasswdFile(c.password_file)
  File "c:\python27\lib\site-packages\passlib\apache.py", line 583, in __init__
    super(HtpasswdFile, self).__init__(path, **kwds)
  File "c:\python27\lib\site-packages\passlib\apache.py", line 166, in __init__
    self.load()
  File "c:\python27\lib\site-packages\passlib\apache.py", line 236, in load
    self._load_lines(fh)
  File "c:\python27\lib\site-packages\passlib\apache.py", line 261, in _load_lines
    key, value = parse(line, idx+1)
  File "c:\python27\lib\site-packages\passlib\apache.py", line 590, in _parse_record
    % lineno)
ValueError: malformed htpasswd file (error reading line 1)

see: http://stackoverflow.com/questions/34635226/malformed-htpasswd-file-error-message-when-starting-pypi-server

pypiserver accepts documentation uploads but does not save docs

Not sure how pypiserver is meant to behave with upload_docs but it looks wrong to me.

I am building package docs using sphinx and then running the upload_docs command to upload them to my pypiserver (apache2 and wsgi). I get a 200 response saying that everything went well, but I cannot find the documentation saved on the server and not visible in the index.

Scenario 1 - pypiserver does not support documentation uploads. If this is the case it would be good if it returned a 501 not implemented response so people knew
Scenario 2 - pypiserver is accepting the upload_docs command but is hiding the documentation somewhere. The documentation could be uploaded to describe where the docs get saved, how to view them in the web interface and how to change the documentation folder.

I'd be happy to add some code to do either if theres an agreement on which if these options is correct.

Pete

Allow Search with Pip

This patch hacks the code in order to allow pip search PKG. For example:

pip search  --index http://pypi.intenet.com:8080/search/ MyDjango

I wonder if you are interested on this and if this patch is wellcome for your side.

--- /root/_app.py   2015-03-12 11:16:23.000000000 +0000
+++ /usr/local/lib/python2.7/dist-packages/pypiserver/_app.py   2015-03-12 12:26:29.000000000 +0000
@@ -6,6 +6,7 @@
 import mimetypes
 import logging
 import pkg_resources
+import xml.dom.minidom
 
 try:
     from io import BytesIO
@@ -24,6 +25,48 @@
 log = logging.getLogger('pypiserver.http')
 packages = None
 
+XMLRPC_RESPONSE_SKELETON='''
+
+
+
+
+%(objects)s
+
+
+
+'''
+
+def from_obj_to_xmlrpc(obj_):
+    res = ""
+    if isinstance(obj_,int):
+        res += "%s" % obj_
+        return res
+    elif isinstance(obj_,str):
+        res += "%s" % obj_
+        return res
+    elif isinstance(obj_,dict):
+        res += ""
+        for k,v in obj_.iteritems():
+            member = {}
+            member["name"]=k
+            member["value"]=from_obj_to_xmlrpc(v)
+            res_1 = ""
+            res_1 += "%(name)s"
+            res_1 += "%(value)s"
+            res_1 += ""
+            res += res_1 % member
+        res += ""
+        return res
+    elif isinstance(obj_,list):
+        res += ""
+        for i in obj_:
+            res += "%s" % from_obj_to_xmlrpc(i)
+        res += ""
+        return res
+    else:
+       raise Exception("No valid object")
+
+
 
 class Configuration(object):
     def __init__(self):
@@ -267,8 +310,31 @@
     return redirect(request.fullpath + "/")
 
 
[email protected]("/simple/")
[email protected]('/search')
[email protected]('/search/')
 @auth("list")
+def search():
+    value = ""
+    try:
+        parser = xml.dom.minidom.parse(request.body)
+        member = parser.getElementsByTagName("member")[0]
+        value  = parser.getElementsByTagName("string")[0].childNodes[0].wholeText.strip()
+    except Exception, e:
+        value = ""
+
+    response = []
+    ordering = 0
+    for p in packages():
+        if p.pkgname.count(value) > 0:
+            d = {'_pypi_ordering': ordering, 'version': p.version,
+                 'name': p.pkgname, 'summary': p.fn}
+            response.append(d)
+        ordering += 1
+    res = XMLRPC_RESPONSE_SKELETON \
+        % {"objects":from_obj_to_xmlrpc(response)}
+    return res
+
[email protected]("/simple/")
 def simpleindex():
     links = sorted(get_prefixes(packages()))
     tmpl = """\

missing distribution spec [pip 1.5.6, python 2.7]

Hi,

I run into this error when using a newer version of pip.

pip 1.5.4 from /usr/lib/python2.7/dist-packages (python 2.7)

root@bc36f17fe2cc:/# pip install -r http://my-pypiserver/simple/ my-package
Exception:
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
    status = self.run(options, args)
  File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 262, in run
    for req in parse_requirements(filename, finder=finder, options=options, session=session):
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1631, in parse_requirements
    req = InstallRequirement.from_line(line, comes_from, prereleases=getattr(options, "pre", None))
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 172, in from_line
    return cls(req, comes_from, url=url, prereleases=prereleases)
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 70, in __init__
    req = pkg_resources.Requirement.parse(req)
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2667, in parse
    reqs = list(parse_requirements(s))
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2593, in parse_requirements
    raise ValueError("Missing distribution spec", line)
ValueError: ('Missing distribution spec', '<html><head><title>Simple Index</title></head><body>')

When using pip 1.3.x (don't recall the exact version), it works just fine.

Undeclared dependency

The passlib package is required and (if not present) will cause the application to crash when the password_file parameter is passed to app(). Simplest fix is probably just to add this as a dependency when building your distribution.

Nested directory structure for storing packages

Now all packages are stored in a single directory. If the server has too many packages with numerous releases, the number of files will be very huge. It would be good to organize the files in a directory structure based on package name. This need not be the default behavior, it can be a configurable.

For example:

packages/
   hello/
     hello-1.0.tar.gz
     hello-1.1.tar.gz
   another/
     another-1.0.tar.gz
     another-2.0.tar.gz

PyPI backend and redirections

Hi, thanks for pypiserver, simple and useful !

Here's a tricky problem when running pypiserver with fallback to a mirror index, not sure if it should be fixed within pypiserver or not.
See also https://bitbucket.org/loewis/pep381client/issue/22

The main PyPI server does some 301 redirections (to fix some mispellings). That's not something a mirror can easily reproduce (see above cited issue on pep381client).
The combination of pypiserver and a mirror leads to installation errors.
Fixing one's spellings is not practically possible, because they occur a lot through dependencies.

Reproduction

Assume for instance that pypiserver does not hold packages for 'babel'.

Client applications (such as pip) try e.g., '/simple/babel' (proper spelling is 'Babel')

  • On the main PyPI, they get a 301 response to '/simple/Babel' -> ok
  • On a PyPI mirror, they get a 404, then they fetch the whole '/simple/' page, analyse it, find 'Babel' in it, correct the spelling and retry -> inefficient, but ok
  • On pypiserver with fallback on a mirror, they get:
    • a 303 to the mirror ('/simple/babel')
    • then, a 404 from the mirror
    • then they fetch the '/simple' page from pypiserver, which does not list the wished distribution ('Babel') -> ERROR

Workarounds

My workaround for now is to setup 301 redirections for commonly mispelled distributions in the mirror as well (in our case, the mirror is ours), but that's a maintenance burden and does not scale.

Another possibility is to manually add commonly mispelled distributions in pypiserver and use '-U'. That's insatisfactoy for the same reasons.

Conclusion

Mispellings in dependencies are really common, since many distribution authors don't even realize their spelling is wrong. Any idea ?

Will be building a RPM package for Fedora, interested in coop?

Hi,

it will be necessary in our company to run our own pypiserver. To improve the work for the admins we want to build rpm packages for them. Would you guys be interested in cooperating?

Currently I have a shell script which creates a virtualenv location and a package location, starts the virtualenv and installs a new pypiserver, then runs it on a configured port. Additionally I've created a systemd service file which enables automatic startup for the package service. The next step will be putting all of that into a RPM spec file and finding a service that always builds a new package when the shell script or the service file change. I think that a public rpm builder would be okay and that the pypiserver repo would be a reasonable location for these files. What do you guys think?

Can't list packages on Windows

The actual documentation states that in order to start the server, one should do:

pip install pypiserver
mkdir ~/packages
# copy some source packages or eggs to this directory
pypi-server -p 8080 ~/packages
pip install -i http://localhost:8080/simple/ ...

When installing pypiserver on Windows, the fourth line results in the following error:

Error: while trying to list 'C:\Program Files\Python\Scripts~\packages': [WinError 3] The system cannot find the path specified: 'C:\Program Files\Python\Scripts~\packages_._'

Replacing:

pypi-server -p 8080 ~/packages

by:

pypi-server -p 8080 packages

works.

Wouldn't it be nice to include in the documentation a note about this error on Windows and the possible way to avoid it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.