├── .coveragerc ├── .github ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── .travis.yml ├── CHANGES.rst ├── LICENSE ├── MANIFEST.in ├── README.rst ├── docs ├── Makefile ├── are_docs_changed.sh └── source │ ├── _static │ └── .gitkeep │ ├── awslimitchecker.html │ ├── changes.rst │ ├── conf.py │ ├── example_output.rst │ ├── index.rst │ ├── modules.rst │ ├── pypi_download_stats.dataquery.rst │ ├── pypi_download_stats.diskdatacache.rst │ ├── pypi_download_stats.graphs.rst │ ├── pypi_download_stats.outputgenerator.rst │ ├── pypi_download_stats.projectstats.rst │ ├── pypi_download_stats.rst │ ├── pypi_download_stats.runner.rst │ └── pypi_download_stats.version.rst ├── pypi_download_stats ├── __init__.py ├── dataquery.py ├── diskdatacache.py ├── graphs.py ├── outputgenerator.py ├── projectstats.py ├── runner.py ├── templates │ ├── badges.html │ ├── base.html │ ├── graph_macro.html │ └── nav.html ├── tests │ ├── __init__.py │ ├── test_runner.py │ └── test_version.py └── version.py ├── pytest.ini ├── setup.cfg ├── setup.py └── tox.ini /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | branch = True 3 | omit = lib/* 4 | pypi-download-stats/tests/* 5 | setup.py 6 | 7 | [report] 8 | exclude_lines = 9 | # this cant ever be run by py.test, but it just calls one function, 10 | # so ignore it 11 | if __name__ == .__main__.: 12 | if sys.version_info.+ 13 | raise NotImplementedError 14 | except ImportError: 15 | .*# nocoverage.* 16 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Contributing to pypi-download-stats 2 | =============================== 3 | 4 | See the [Documentation on ReadTheDocs](http://pypi-download-stats.readthedocs.org/en/master/index.html) for information on how to contribute. 5 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Please remove all of this template but the relevant section below, and fill in 2 | each item in that section. 3 | 4 | ## Feature Request 5 | 6 | ### Feature Description 7 | 8 | Describe in detail the feature you would like to see implemented, especially 9 | how it would work from a user perspective and what benefits it adds. Your description 10 | should be detailed enough to be used to determine if code written for the feature 11 | adequately solves the problem. 12 | 13 | ### Use Cases 14 | 15 | Describe one or more use cases for why this feature will be useful. 16 | 17 | ### Testing Assistance 18 | 19 | Indicate whether or not you will be able to assist in testing pre-release 20 | code for the feature. 21 | 22 | ## Bug Report 23 | 24 | When reporting a bug, please provide all of the following information, 25 | as well as any additional details that may be useful in reproducing or fixing 26 | the issue: 27 | 28 | ### Version 29 | 30 | python-project-skeleton version, as reported by ``python-project-skeleton --version`` 31 | 32 | ### Installation Method 33 | 34 | How was python-project-skeleton installed (provide as much detail as possible, ideally 35 | the exact command used and whether it was installed in a virtualenv or not). 36 | 37 | ### Supporting Software Versions 38 | 39 | The output of ``python --version`` and ``virtualenv --version`` in the environment 40 | that python-project-skeleton is running in, as well as your operating system type and version. 41 | 42 | ### Actual Output 43 | 44 | ``` 45 | Paste here the output of python-project-skeleton (including the command used to run it), 46 | run with the -vv (debug-level output) flag, that shows the issue. 47 | ``` 48 | 49 | ### Expected Output 50 | 51 | Describe the output that you expected (what's wrong). If possible, after your description, 52 | copy the actual output above and modify it to what was expected. 53 | 54 | ### Testing Assistance 55 | 56 | Indicate whether or not you will be able to assist in testing pre-release 57 | code for the feature. 58 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | __IMPORTANT:__ Please take note of the below checklist, especially the first two items. 2 | 3 | # Pull Request Checklist 4 | 5 | - [ ] All pull requests must include the Contributor License Agreement (see below). 6 | - [ ] Code should conform to the following: 7 | - [ ] pep8 compliant with some exceptions (see pytest.ini) 8 | - [ ] 100% test coverage with pytest (with valid tests). If you have difficulty 9 | writing tests for the code, feel free to ask for help or submit the PR without tests. 10 | - [ ] Complete, correctly-formatted documentation for all classes, functions and methods. 11 | - [ ] documentation has been rebuilt with ``tox -e docs`` 12 | - [ ] All modules should have (and use) module-level loggers. 13 | - [ ] **Commit messages** should be meaningful, and reference the Issue number 14 | if you're working on a GitHub issue (i.e. "issue #x - "). Please 15 | refrain from using the "fixes #x" notation unless you are *sure* that the 16 | the issue is fixed in that commit. 17 | - [ ] Git history is fully intact; please do not squash or rewrite history. 18 | 19 | ## Contributor License Agreement 20 | 21 | By submitting this work for inclusion in awslimitchecker, I agree to the following terms: 22 | 23 | * The contribution included in this request (and any subsequent revisions or versions of it) 24 | is being made under the same license as the awslimitchecker project (the Affero GPL v3, 25 | or any subsequent version of that license if adopted by awslimitchecker). 26 | * My contribution may perpetually be included in and distributed with awslimitchecker; submitting 27 | this pull request grants a perpetual, global, unlimited license for it to be used and distributed 28 | under the terms of awslimitchecker's license. 29 | * I have the legal power and rights to agree to these terms. 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | bin/ 12 | include/ 13 | env/ 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | pip-selfcheck.json 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *,cover 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | 57 | # Sphinx documentation 58 | docs/build/ 59 | 60 | # PyBuilder 61 | target/ 62 | 63 | # virtualenv 64 | bin/ 65 | include/ 66 | 67 | .idea/ 68 | 69 | pypi-stats-cache/ 70 | pypi-stats/ 71 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | sudo: false 3 | 4 | cache: pip 5 | 6 | matrix: 7 | include: 8 | - python: "2.7" 9 | env: TOXENV=py27 10 | - python: "3.5" 11 | env: TOXENV=py35 12 | - python: "3.6" 13 | env: TOXENV=py36 14 | - python: "2.7" 15 | env: TOXENV=docs 16 | 17 | install: 18 | - virtualenv --version 19 | - git config --global user.email "travisci@jasonantman.com" 20 | - git config --global user.name "travisci" 21 | - pip install tox 22 | - pip install codecov 23 | - pip freeze 24 | - virtualenv --version 25 | script: 26 | - tox -r 27 | 28 | after_success: 29 | - codecov 30 | 31 | notifications: 32 | email: 33 | on_success: always 34 | on_failure: always 35 | pushover: 36 | users: 37 | - secure: "SA0nU9p4+7+qBPLtijwmiAJXwx4hEWxyA+qnJ4jTTYD+XWmli479DIC6oiiyvSpYDDolthBf6D3mcEM1V3zMWE9mP5SCGEK+oj/vloLBT8XAV1nhedS4HXgOIqacIAstN4WmURLOBZfrMUF27UlAJ257wPCdD7DHcu8dNnUXAt6alK2PPFdz126UkN3PjTHPqRgVk0YuT6nz2d9ugbgvyp6ljDt1raf8hTy2h9GgrF2nxr3+H5o4cKf28HNQd0y4kFzRUVJ3B+lhYkPnc/JjFGRQYDncTVgAmY2DjXR0LX+Dn074WC2NsDL4mb2cTtmDoudkx02JCVeKOG1646faS1gQyMJAgrelFIcVmGfdJMIDODfX2/g3tRS5zbEF6RuLKb75BaKaV6w1FjX9vyB1f75kHkAZfVrmofkz0A2lH2sR94XhDP2oZOlgCP9NvZtoc2TYVz8XxWrYcIqesE06ILVwYHcH6E0atiDAJLzBPFnlcxj1T4o1JsE+NhsEhJnU+GHuiF+OoMEkDkdmzLIdR3Fy41+JLWwE6ujS3ZaOQNonWeI8bTZNjNbPCD8MQdE1K86gqNQYGyyB7ZDbLQZcj3nXGdNJiTHXCoyg1tniNRRdh/BcBPSV5PQnjLfukBtB3Fuldm1WP2wt4QitBULKtkrRf5SeIJNOph3cU2EKpV8=" 38 | api_key: 39 | secure: "hxa8cZjs4VskXYaO28pz5DUEBdJK61MseRJ11HS7fNU5xZ1LCGxqIc86k7ekzk9/R4p6tF3QtdgK6BDAOawOa15IetX0MqbKrSHVxJ34l2i1xnRnU8LZpZAwFh/ZzQ58B/vRWouu2oCWDnQGM4jkYEeD+GJXofV+CkCAmB4ut0ujvps9eD5GIGzlzZZ0WV4B1KTeRhOLcqT5ch/GfkDHKBb6QXLKP27yufifuwoBjTahsPnzVfL6enFlQP/1lFidW2P/Jpd92uTdQsp0EkiLsjaWhyAWB1o7i+QKnEhxDlOaM3Dh6tofGh0J4KIbKX6+qxvQ9cHr829NebyLiuJTdSY4sSfsxavKZHBEc1vKoAPNtG1E6reXPKD5lZi/UQsMGB56AIuVn+IZ0fvNKex558WZKfi/ebUbdyskT1p4l8aYPT4mQ69tp8SRcG9a5nHB32aXc5gCAEHrtsWuT0peZx34G2ifj4aqUEnKvlbvJ4ALlrC9HfuVsn3g4hCflF3G2IHdogvgkA9NWg6RA7moKJCkRDSx0GnozcaAcmntnUckBMjrB6VQWN/Bd1qQX5m96/IwSHWtRERRTB2bVwWX0UtNZ3N+ZNgEUQYQnZk4NSP6xRj8RDt+KP2zmP8QnsETl4Ry0t0QMB9YO04Bwih6o7gTCVa1Wj8a+kemC+a8A6w=" 40 | branches: 41 | except: 42 | - "/^noci-.*$/" 43 | -------------------------------------------------------------------------------- /CHANGES.rst: -------------------------------------------------------------------------------- 1 | Changelog 2 | ========= 3 | 4 | Unreleased Changes 5 | ------------------ 6 | 7 | * Stop testing and supporting py33; start testing py36. 8 | * Stop testing and supporting py34, as we rely on ``pandas`` that doesn't support 3.4. 9 | * Many fixes for pep8/flakes and docs build. 10 | 11 | 0.2.1 (2016-09-18) 12 | ------------------ 13 | 14 | * Fix example cron S3 upload script in README. 15 | 16 | 0.2.0 (2016-09-18) 17 | ------------------ 18 | 19 | * Fix packaging bug where HTML templates weren't included in package (making 20 | this entire tool pretty useless) 21 | * Fix unicode output error. 22 | 23 | 0.1.0 (2016-08-28) 24 | ------------------ 25 | 26 | * Initial release 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | 663 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include CHANGES.rst 2 | include LICENSE 3 | include README.rst 4 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | DEPRECATED - pypi-download-stats 2 | ================================ 3 | 4 | .. image:: https://img.shields.io/pypi/v/pypi-download-stats.svg 5 | :target: https://pypi.python.org/pypi/pypi-download-stats 6 | :alt: PyPi package version 7 | 8 | .. image:: https://img.shields.io/github/forks/jantman/pypi-download-stats.svg 9 | :alt: GitHub Forks 10 | :target: https://github.com/jantman/pypi-download-stats/network 11 | 12 | .. image:: https://img.shields.io/github/issues/jantman/pypi-download-stats.svg 13 | :alt: GitHub Open Issues 14 | :target: https://github.com/jantman/pypi-download-stats/issues 15 | 16 | .. image:: https://secure.travis-ci.org/jantman/pypi-download-stats.png?branch=master 17 | :target: http://travis-ci.org/jantman/pypi-download-stats 18 | :alt: travis-ci for master branch 19 | 20 | .. image:: https://readthedocs.org/projects/pypi-download-stats/badge/?version=latest 21 | :target: https://readthedocs.org/projects/pypi-download-stats/?badge=latest 22 | :alt: sphinx documentation for latest release 23 | 24 | .. image:: https://www.repostatus.org/badges/latest/abandoned.svg 25 | :alt: Project Status: Abandoned – Initial development has started, but there has not yet been a stable, usable release; the project has been abandoned and the author(s) do not intend on continuing development. 26 | :target: https://www.repostatus.org/#abandoned 27 | 28 | IMPORTANT - PROJECT ABANDONED 29 | ----------------------------- 30 | 31 | A quick Google search indicates that there are now multiple websites, such as `PyPiStats.org `_ that provide this information. As such, I'm abandoning this project. 32 | 33 | Introduction 34 | ------------ 35 | 36 | This package retrieves download statistics from Google BigQuery for one or more 37 | `PyPI `_ packages, caches them locally, and then 38 | generates download count badges as well as an HTML page of raw data and graphs 39 | (generated by `bokeh `_ ). It's intended to 40 | be run on a schedule (i.e. daily) and have the results uploaded somewhere. 41 | 42 | It would certainly be nice to make this into a real service (and some extension 43 | points for that have been included), but at the moment 44 | I have neither the time to dedicate to that, the money to cover some sort 45 | of hosting and bandwidth, nor the desire to handle how to architect this for 46 | over 85,000 projects as opposed to my few. 47 | 48 | Hopefully stats like these will eventually end up in the official PyPI; see 49 | warehouse `#699 `_, 50 | `#188 `_ and 51 | `#787 `_ for reference on that work. 52 | For the time being, I want to (a) give myself a way to get simple download stats 53 | and badges like the old PyPI legacy (downloads per day, week and month) as well 54 | as (b) enable some higher-granularity analysis. 55 | 56 | **Note** that this is a relatively heavy-weight solution; it has many dependencies and is really intended for people whose main need is to generate detailed historical graphs and download count badges for their projects. If your really just want to perform some ad-hoc queries, counts, or simple data analysis on the PyPI downloads dataset, a project like `Ofek's pypinfo `_ would be a simpler alternative. 57 | 58 | **Also note** this package is *very* young; I wrote it as an evening/weekend project, 59 | hoping to only take a few days on it. Though writing this makes me want to bathe 60 | immediately, it has no tests. If people start using it, I'll change that. 61 | 62 | For a live example of exactly how the output looks, you can see the download 63 | stats page for my awslimitchecker project, generated by a cronjob on my desktop, 64 | at: `http://jantman-personal-public.s3-website-us-east-1.amazonaws.com/pypi-stats/awslimitchecker/index.html `_. 65 | 66 | Background 67 | ---------- 68 | 69 | Sometime in February 2016, `download stats `_ 70 | stopped working on pypi.python.org. As I later learned, what we currently (August 2016) 71 | know as pypi is really the `pypi-legacy `_ codebase, 72 | and is far from a stable hands-off service. The `small team of interpid souls `_ 73 | who keep it running have their hands full simply keeping it online, while also working 74 | on its replacement, `warehouse `_ (which as of August 2016 is available online 75 | at `https://pypi.io/ `_). While the actual pypi.python.org web UI hasn't been 76 | switched over to the warehouse code yet (it's still under development), the current Warehouse 77 | service does provide full access to pypi. It's completely understandable that, given all this 78 | and the "life support" status of the legacy pypi codebase, download stats in a legacy codebase 79 | are their last concern. 80 | 81 | However, current download statistics (actually the raw log information) since January 22, 2016 82 | are `available in a Google BigQuery public dataset `_ 83 | and being updated in near-real-time. There may be download statistics functionality 84 | 85 | Requirements 86 | ------------ 87 | 88 | * Python 2.7+ (currently tested with 2.7, 3.5, 3.6) 89 | * Python `VirtualEnv `_ and ``pip`` (recommended installation method; your OS/distribution should have packages for these) 90 | 91 | pypi-download-stats relies on `bokeh `_ to generate 92 | pretty SVG charts that work offline, and 93 | `google-api-python-client `_ 94 | for querying BigQuery. Each of those have additional dependencies. 95 | 96 | Installation 97 | ------------ 98 | 99 | It's recommended that you install into a virtual environment (virtualenv / 100 | venv). See the `virtualenv usage documentation `_ 101 | for information on how to create a venv. 102 | 103 | This isn't on pypi yet, ironically. Until it is: 104 | 105 | .. code-block:: bash 106 | 107 | $ pip install pypi-download-stats 108 | 109 | Configuration 110 | ------------- 111 | 112 | You'll need Google Cloud credentials for a project that has the BigQuery API 113 | enabled. The recommended method is to generate system account credentials; 114 | download the JSON file for the credentials and export the path to it as the 115 | ``GOOGLE_APPLICATION_CREDENTIALS`` environment variable. The system account 116 | will need to be added as a Project Member. 117 | 118 | Usage 119 | ----- 120 | 121 | Run with ``-h`` for command-line help:: 122 | 123 | usage: pypi-download-stats [-h] [-V] [-v] [-Q | -G] [-o OUT_DIR] 124 | [-p PROJECT_ID] [-c CACHE_DIR] [-B BACKFILL_DAYS] 125 | [-P PROJECT | -U USER] 126 | 127 | pypi-download-stats - Calculate detailed download stats and generate HTML and 128 | badges for PyPI packages - 129 | 130 | optional arguments: 131 | -h, --help show this help message and exit 132 | -V, --version show program's version number and exit 133 | -v, --verbose verbose output. specify twice for debug-level output. 134 | -Q, --no-query do not query; just generate output from cached data 135 | -G, --no-generate do not generate output; just query data and cache 136 | results 137 | -o OUT_DIR, --out-dir OUT_DIR 138 | output directory (default: ./pypi-stats 139 | -p PROJECT_ID, --project-id PROJECT_ID 140 | ProjectID for your Google Cloud user, if not using 141 | service account credentials JSON file 142 | -c CACHE_DIR, --cache-dir CACHE_DIR 143 | stats cache directory (default: ./pypi-stats-cache) 144 | -B BACKFILL_DAYS, --backfill-num-days BACKFILL_DAYS 145 | number of days of historical data to backfill, if 146 | missing (defaut: 7). Note this may incur BigQuery 147 | charges. Set to -1 to backfill all available history. 148 | -P PROJECT, --project PROJECT 149 | project name to query/generate stats for (can be 150 | specified more than once; this will reduce query cost 151 | for multiple projects) 152 | -U USER, --user USER Run for all PyPI projects owned by the specifieduser. 153 | 154 | To run queries and generate reports for PyPI projects "foo" and "bar", using a 155 | Google Cloud credentials JSON file at ``foo.json``: 156 | 157 | .. code-block:: bash 158 | 159 | $ export GOOGLE_APPLICATION_CREDENTIALS=/foo.json 160 | $ pypi-download-stats -P foo -P bar 161 | 162 | To run queries but *not* generate reports for all PyPI projects owned by user 163 | "myname": 164 | 165 | .. code-block:: bash 166 | 167 | $ export GOOGLE_APPLICATION_CREDENTIALS=/foo.json 168 | $ pypi-download-stats -G -U myname 169 | 170 | To generate reports against cached query data for the project "foo": 171 | 172 | .. code-block:: bash 173 | 174 | $ export GOOGLE_APPLICATION_CREDENTIALS=/foo.json 175 | $ pypi-download-stats -Q -P foo 176 | 177 | To run nightly and upload results to a website-hosting S3 bucket, I use the 178 | following script via cron (note the paths are specific to my purpose; also note 179 | the two commands, as ``s3cmd`` does not seem to set the MIME type for the SVG 180 | images correctly): 181 | 182 | .. code-block:: bash 183 | 184 | #!/bin/bash -x 185 | 186 | export GOOGLE_APPLICATION_CREDENTIALS=/home/jantman/.ssh/pypi-bigquery.json 187 | cd /home/jantman/GIT/pypi-download-stats 188 | bin/pypi-download-stats -vv -U jantman 189 | 190 | # sync html files 191 | ~/venvs/foo/bin/s3cmd -r --delete-removed --stats --exclude='*.svg' sync pypi-stats s3://jantman-personal-public/ 192 | # sync SVG and set mime-type, since s3cmd gets it wrong 193 | ~/venvs/foo/bin/s3cmd -r --delete-removed --stats --exclude='*.html' --mime-type='image/svg+xml' sync pypi-stats s3://jantman-personal-public/ 194 | 195 | Cost 196 | ++++ 197 | 198 | At this point... I have no idea. Some of the download tables are 3+ GB per day. 199 | I imagine that backfilling historical data from the beginning of what's currently 200 | there (20160122) might incur quite a bit of data cost. 201 | 202 | Bugs and Feature Requests 203 | ------------------------- 204 | 205 | Bug reports and feature requests are happily accepted via the `GitHub Issue Tracker `_. Pull requests are 206 | welcome. Issues that don't have an accompanying pull request will be worked on 207 | as my time and priority allows. 208 | 209 | Development 210 | =========== 211 | 212 | To install for development: 213 | 214 | 1. Fork the `pypi-download-stats `_ repository on GitHub 215 | 2. Create a new branch off of master in your fork. 216 | 217 | .. code-block:: bash 218 | 219 | $ virtualenv pypi-download-stats 220 | $ cd pypi-download-stats && source bin/activate 221 | $ pip install -e git+git@github.com:YOURNAME/pypi-download-stats.git@BRANCHNAME#egg=pypi-download-stats 222 | $ cd src/pypi-download-stats 223 | 224 | The git clone you're now in will probably be checked out to a specific commit, 225 | so you may want to ``git checkout BRANCHNAME``. 226 | 227 | Guidelines 228 | ---------- 229 | 230 | * pep8 compliant with some exceptions (see pytest.ini) 231 | 232 | Testing 233 | ------- 234 | 235 | There isn't any right now. I'm bad. If people actually start using this, I'll 236 | refactor and add tests, but for now this started as a one-night project. 237 | 238 | Release Checklist 239 | ----------------- 240 | 241 | 1. Open an issue for the release; cut a branch off master for that issue. 242 | 2. Confirm that there are CHANGES.rst entries for all major changes. 243 | 3. Ensure that Travis tests passing in all environments. 244 | 4. Ensure that test coverage is no less than the last release (ideally, 100%). 245 | 5. Increment the version number in pypi-download-stats/version.py and add version and release date to CHANGES.rst, then push to GitHub. 246 | 6. Confirm that README.rst renders correctly on GitHub. 247 | 7. Upload package to testpypi: 248 | 249 | * Make sure your ~/.pypirc file is correct (a repo called ``test`` for https://testpypi.python.org/pypi) 250 | * ``rm -Rf dist`` 251 | * ``python setup.py register -r https://testpypi.python.org/pypi`` 252 | * ``python setup.py sdist bdist_wheel`` 253 | * ``twine upload -r test dist/*`` 254 | * Check that the README renders at https://testpypi.python.org/pypi/pypi-download-stats 255 | 256 | 8. Create a pull request for the release to be merged into master. Upon successful Travis build, merge it. 257 | 9. Tag the release in Git, push tag to GitHub: 258 | 259 | * tag the release. for now the message is quite simple: ``git tag -a X.Y.Z -m 'X.Y.Z released YYYY-MM-DD'`` 260 | * push the tag to GitHub: ``git push origin X.Y.Z`` 261 | 262 | 11. Upload package to live pypi: 263 | 264 | * ``twine upload dist/*`` 265 | 266 | 10. make sure any GH issues fixed in the release were closed. 267 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " applehelp to make an Apple Help Book" 34 | @echo " devhelp to make HTML files and a Devhelp project" 35 | @echo " epub to make an epub" 36 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 37 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 38 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 39 | @echo " text to make text files" 40 | @echo " man to make manual pages" 41 | @echo " texinfo to make Texinfo files" 42 | @echo " info to make Texinfo files and run them through makeinfo" 43 | @echo " gettext to make PO message catalogs" 44 | @echo " changes to make an overview of all changed/added/deprecated items" 45 | @echo " xml to make Docutils-native XML files" 46 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 47 | @echo " linkcheck to check all external links for integrity" 48 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 49 | @echo " coverage to run coverage check of the documentation (if enabled)" 50 | 51 | clean: 52 | rm -rf $(BUILDDIR)/* 53 | 54 | html: 55 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 56 | @echo 57 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 58 | 59 | dirhtml: 60 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 61 | @echo 62 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 63 | 64 | singlehtml: 65 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 66 | @echo 67 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 68 | 69 | pickle: 70 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 71 | @echo 72 | @echo "Build finished; now you can process the pickle files." 73 | 74 | json: 75 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 76 | @echo 77 | @echo "Build finished; now you can process the JSON files." 78 | 79 | htmlhelp: 80 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 81 | @echo 82 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 83 | ".hhp project file in $(BUILDDIR)/htmlhelp." 84 | 85 | qthelp: 86 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 87 | @echo 88 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 89 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 90 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pypi-download-stats.qhcp" 91 | @echo "To view the help file:" 92 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pypi-download-stats.qhc" 93 | 94 | applehelp: 95 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 96 | @echo 97 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 98 | @echo "N.B. You won't be able to view it unless you put it in" \ 99 | "~/Library/Documentation/Help or install it in your application" \ 100 | "bundle." 101 | 102 | devhelp: 103 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 104 | @echo 105 | @echo "Build finished." 106 | @echo "To view the help file:" 107 | @echo "# mkdir -p $$HOME/.local/share/devhelp/pypi-download-stats" 108 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pypi-download-stats" 109 | @echo "# devhelp" 110 | 111 | epub: 112 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 113 | @echo 114 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 115 | 116 | latex: 117 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 118 | @echo 119 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 120 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 121 | "(use \`make latexpdf' here to do that automatically)." 122 | 123 | latexpdf: 124 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 125 | @echo "Running LaTeX files through pdflatex..." 126 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 127 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 128 | 129 | latexpdfja: 130 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 131 | @echo "Running LaTeX files through platex and dvipdfmx..." 132 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 133 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 134 | 135 | text: 136 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 137 | @echo 138 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 139 | 140 | man: 141 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 142 | @echo 143 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 144 | 145 | texinfo: 146 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 147 | @echo 148 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 149 | @echo "Run \`make' in that directory to run these through makeinfo" \ 150 | "(use \`make info' here to do that automatically)." 151 | 152 | info: 153 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 154 | @echo "Running Texinfo files through makeinfo..." 155 | make -C $(BUILDDIR)/texinfo info 156 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 157 | 158 | gettext: 159 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 160 | @echo 161 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 162 | 163 | changes: 164 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 165 | @echo 166 | @echo "The overview file is in $(BUILDDIR)/changes." 167 | 168 | linkcheck: 169 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 170 | @echo 171 | @echo "Link check complete; look for any errors in the above output " \ 172 | "or in $(BUILDDIR)/linkcheck/output.txt." 173 | 174 | doctest: 175 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 176 | @echo "Testing of doctests in the sources finished, look at the " \ 177 | "results in $(BUILDDIR)/doctest/output.txt." 178 | 179 | coverage: 180 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 181 | @echo "Testing of coverage in the sources finished, look at the " \ 182 | "results in $(BUILDDIR)/coverage/python.txt." 183 | 184 | xml: 185 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 186 | @echo 187 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 188 | 189 | pseudoxml: 190 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 191 | @echo 192 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 193 | -------------------------------------------------------------------------------- /docs/are_docs_changed.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | # helper to check and see if there are uncommitted git changes to docs 3 | 4 | DOC_SOURCE=$1 5 | 6 | function dirty { 7 | >&2 echo "ERROR: generating documentation results in uncommitted changes; please re-generate and commit docs locally" 8 | git diff --no-ext-diff --exit-code $DOC_SOURCE 9 | git diff-index --cached HEAD -- $DOC_SOURCE 10 | exit 1 11 | } 12 | 13 | git diff --no-ext-diff --quiet --exit-code $DOC_SOURCE || dirty 14 | git diff-index --cached --quiet HEAD -- $DOC_SOURCE || dirty 15 | exit 0 16 | -------------------------------------------------------------------------------- /docs/source/_static/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jantman/pypi-download-stats/c29635f856a540ceb806412778e3ac2cbb31abcf/docs/source/_static/.gitkeep -------------------------------------------------------------------------------- /docs/source/changes.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../../CHANGES.rst 2 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # pypi-download-stats documentation build configuration file, created by 4 | # sphinx-quickstart on Sat Jun 6 16:12:56 2015. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys 16 | import os 17 | import re 18 | # to let sphinx find the actual source... 19 | sys.path.insert(0, os.path.abspath("../..")) 20 | from pypi_download_stats.version import VERSION 21 | import sphinx.environment 22 | from docutils.utils import get_source_line 23 | 24 | # If extensions (or modules to document with autodoc) are in another directory, 25 | # add these directories to sys.path here. If the directory is relative to the 26 | # documentation root, use os.path.abspath to make it absolute, like shown here. 27 | #sys.path.insert(0, os.path.abspath('.')) 28 | 29 | is_rtd = os.environ.get('READTHEDOCS', None) != 'True' 30 | readthedocs_version = os.environ.get('READTHEDOCS_VERSION', '') 31 | 32 | rtd_version = VERSION 33 | 34 | if (readthedocs_version in ['stable', 'latest', 'master'] or 35 | re.match(r'^\d+\.\d+\.\d+', readthedocs_version)): 36 | # this is a tag or stable/latest/master; show the actual version 37 | rtd_version = VERSION 38 | 39 | # -- General configuration ------------------------------------------------ 40 | 41 | # If your documentation needs a minimal Sphinx version, state it here. 42 | #needs_sphinx = '1.0' 43 | 44 | # Add any Sphinx extension module names here, as strings. They can be 45 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 46 | # ones. 47 | extensions = [ 48 | 'sphinx.ext.autodoc', 49 | 'sphinx.ext.intersphinx', 50 | 'sphinx.ext.todo', 51 | 'sphinx.ext.coverage', 52 | 'sphinx.ext.viewcode', 53 | ] 54 | 55 | # Add any paths that contain templates here, relative to this directory. 56 | templates_path = ['_templates'] 57 | 58 | # The suffix(es) of source filenames. 59 | # You can specify multiple suffix as a list of string: 60 | # source_suffix = ['.rst', '.md'] 61 | source_suffix = '.rst' 62 | 63 | # The encoding of source files. 64 | #source_encoding = 'utf-8-sig' 65 | 66 | # The master toctree document. 67 | master_doc = 'index' 68 | 69 | # General information about the project. 70 | project = u'pypi-download-stats' 71 | copyright = u'2016 Jason Antman' 72 | author = u'Jason Antman' 73 | 74 | # The version info for the project you're documenting, acts as replacement for 75 | # |version| and |release|, also used in various other places throughout the 76 | # built documents. 77 | # 78 | # The short X.Y version. 79 | version = rtd_version 80 | # The full version, including alpha/beta/rc tags. 81 | release = version 82 | 83 | # The language for content autogenerated by Sphinx. Refer to documentation 84 | # for a list of supported languages. 85 | # 86 | # This is also used if you do content translation via gettext catalogs. 87 | # Usually you set "language" from the command line for these cases. 88 | language = None 89 | 90 | # There are two options for replacing |today|: either, you set today to some 91 | # non-false value, then it is used: 92 | #today = '' 93 | # Else, today_fmt is used as the format for a strftime call. 94 | #today_fmt = '%B %d, %Y' 95 | 96 | # List of patterns, relative to source directory, that match files and 97 | # directories to ignore when looking for source files. 98 | exclude_patterns = [] 99 | 100 | # The reST default role (used for this markup: `text`) to use for all 101 | # documents. 102 | #default_role = None 103 | 104 | # If true, '()' will be appended to :func: etc. cross-reference text. 105 | #add_function_parentheses = True 106 | 107 | # If true, the current module name will be prepended to all description 108 | # unit titles (such as .. function::). 109 | #add_module_names = True 110 | 111 | # If true, sectionauthor and moduleauthor directives will be shown in the 112 | # output. They are ignored by default. 113 | #show_authors = False 114 | 115 | # The name of the Pygments (syntax highlighting) style to use. 116 | pygments_style = 'sphinx' 117 | 118 | # A list of ignored prefixes for module index sorting. 119 | #modindex_common_prefix = [] 120 | 121 | # If true, keep warnings as "system message" paragraphs in the built documents. 122 | #keep_warnings = False 123 | 124 | # If true, `todo` and `todoList` produce output, else they produce nothing. 125 | todo_include_todos = True 126 | 127 | 128 | # -- Options for HTML output ---------------------------------------------- 129 | 130 | if is_rtd: 131 | import sphinx_rtd_theme 132 | html_theme = 'sphinx_rtd_theme' 133 | html_theme_path = [ 134 | sphinx_rtd_theme.get_html_theme_path(), 135 | ] 136 | html_static_path = ['_static'] 137 | htmlhelp_basename = 'pypi-download-statsdoc' 138 | 139 | #html_theme_options = { 140 | # 'analytics_id': 'Your-ID-Here', 141 | #} 142 | 143 | # The name for this set of Sphinx documents. If None, it defaults to 144 | # " v documentation". 145 | html_title = 'v{v} - Description of Package Here'.format(v=version) 146 | 147 | # Add any extra paths that contain custom files (such as robots.txt or 148 | # .htaccess) here, relative to this directory. These files are copied 149 | # directly to the root of the documentation. 150 | #html_extra_path = [] 151 | 152 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 153 | # using the given strftime format. 154 | html_last_updated_fmt = '%b %d, %Y' 155 | 156 | # If true, SmartyPants will be used to convert quotes and dashes to 157 | # typographically correct entities. 158 | #html_use_smartypants = True 159 | 160 | # Custom sidebar templates, maps document names to template names. 161 | #html_sidebars = {} 162 | 163 | # Additional templates that should be rendered to pages, maps page names to 164 | # template names. 165 | #html_additional_pages = {} 166 | 167 | # If false, no module index is generated. 168 | #html_domain_indices = True 169 | 170 | # If false, no index is generated. 171 | #html_use_index = True 172 | 173 | # If true, the index is split into individual pages for each letter. 174 | #html_split_index = False 175 | 176 | # If true, links to the reST sources are added to the pages. 177 | #html_show_sourcelink = True 178 | 179 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 180 | #html_show_sphinx = True 181 | 182 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 183 | #html_show_copyright = True 184 | 185 | # If true, an OpenSearch description file will be output, and all pages will 186 | # contain a tag referring to it. The value of this option must be the 187 | # base URL from which the finished HTML is served. 188 | #html_use_opensearch = '' 189 | 190 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 191 | #html_file_suffix = None 192 | 193 | # Language to be used for generating the HTML full-text search index. 194 | # Sphinx supports the following languages: 195 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' 196 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' 197 | #html_search_language = 'en' 198 | 199 | # A dictionary with options for the search language support, empty by default. 200 | # Now only 'ja' uses this config value 201 | #html_search_options = {'type': 'default'} 202 | 203 | # The name of a javascript file (relative to the configuration directory) that 204 | # implements a search results scorer. If empty, the default will be used. 205 | #html_search_scorer = 'scorer.js' 206 | 207 | # Output file base name for HTML help builder. 208 | #htmlhelp_basename = 'pypi-download-statsdoc' 209 | 210 | # -- Options for LaTeX output --------------------------------------------- 211 | 212 | latex_elements = { 213 | # The paper size ('letterpaper' or 'a4paper'). 214 | #'papersize': 'letterpaper', 215 | 216 | # The font size ('10pt', '11pt' or '12pt'). 217 | #'pointsize': '10pt', 218 | 219 | # Additional stuff for the LaTeX preamble. 220 | #'preamble': '', 221 | 222 | # Latex figure (float) alignment 223 | #'figure_align': 'htbp', 224 | } 225 | 226 | # Grouping the document tree into LaTeX files. List of tuples 227 | # (source start file, target name, title, 228 | # author, documentclass [howto, manual, or own class]). 229 | latex_documents = [ 230 | (master_doc, 'pypi-download-stats.tex', u'pypi-download-stats Documentation', 231 | u'Jason Antman', 'manual'), 232 | ] 233 | 234 | # The name of an image file (relative to this directory) to place at the top of 235 | # the title page. 236 | #latex_logo = None 237 | 238 | # For "manual" documents, if this is true, then toplevel headings are parts, 239 | # not chapters. 240 | #latex_use_parts = False 241 | 242 | # If true, show page references after internal links. 243 | #latex_show_pagerefs = False 244 | 245 | # If true, show URL addresses after external links. 246 | #latex_show_urls = False 247 | 248 | # Documents to append as an appendix to all manuals. 249 | #latex_appendices = [] 250 | 251 | # If false, no module index is generated. 252 | #latex_domain_indices = True 253 | 254 | 255 | # -- Options for manual page output --------------------------------------- 256 | 257 | # One entry per manual page. List of tuples 258 | # (source start file, name, description, authors, manual section). 259 | man_pages = [ 260 | (master_doc, 'pypi-download-stats', u'pypi-download-stats Documentation', 261 | [author], 1) 262 | ] 263 | 264 | # If true, show URL addresses after external links. 265 | #man_show_urls = False 266 | 267 | 268 | # -- Options for Texinfo output ------------------------------------------- 269 | 270 | # Grouping the document tree into Texinfo files. List of tuples 271 | # (source start file, target name, title, author, 272 | # dir menu entry, description, category) 273 | texinfo_documents = [ 274 | (master_doc, 'pypi-download-stats', u'pypi-download-stats Documentation', 275 | author, 'pypi-download-stats', 'One line description of project.', 276 | 'Miscellaneous'), 277 | ] 278 | 279 | # Documents to append as an appendix to all manuals. 280 | #texinfo_appendices = [] 281 | 282 | # If false, no module index is generated. 283 | #texinfo_domain_indices = True 284 | 285 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 286 | #texinfo_show_urls = 'footnote' 287 | 288 | # If true, do not generate a @detailmenu in the "Top" node's menu. 289 | #texinfo_no_detailmenu = False 290 | 291 | 292 | # Example configuration for intersphinx: refer to the Python standard library. 293 | intersphinx_mapping = { 294 | 'https://docs.python.org/3/': None, 295 | 'http://bokeh.pydata.org/en/0.12.1/': None 296 | } 297 | 298 | autoclass_content = 'class' 299 | autodoc_default_flags = ['members', 'undoc-members', 'private-members', 'show-inheritance'] 300 | 301 | linkcheck_ignore = [ 302 | r'https?://landscape\.io.*', 303 | r'https?://www\.virtualenv\.org.*', 304 | r'https?://.*\.readthedocs\.org.*', 305 | r'https?://codecov\.io.*', 306 | r'https?://.*readthedocs\.org.*', 307 | r'https?://pypi\.python\.org/pypi/pypi-download-stats', 308 | r'https?://testpypi\.python\.org/pypi/pypi-download-stats' 309 | ] 310 | 311 | # exclude module docstrings - see http://stackoverflow.com/a/18031024/211734 312 | def remove_module_docstring(app, what, name, obj, options, lines): 313 | if what == "module": 314 | del lines[:] 315 | 316 | # ignore non-local image warnings 317 | def _warn_node(self, msg, node, **kwargs): 318 | if not msg.startswith('nonlocal image URI found:'): 319 | self._warnfunc(msg, '%s:%s' % get_source_line(node)) 320 | 321 | sphinx.environment.BuildEnvironment.warn_node = _warn_node 322 | 323 | def setup(app): 324 | app.connect("autodoc-process-docstring", remove_module_docstring) 325 | -------------------------------------------------------------------------------- /docs/source/example_output.rst: -------------------------------------------------------------------------------- 1 | Example Output: 2 | =============== 3 | 4 | For a live example of exactly how the output looks, you can see the download 5 | stats page for my awslimitchecker project, generated by a cronjob on my desktop, 6 | at: `http://jantman-personal-public.s3-website-us-east-1.amazonaws.com/pypi-stats/awslimitchecker/index.html `_. 7 | 8 | ---- 9 | 10 | .. raw:: html 11 | :file: awslimitchecker.html 12 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | .. meta:: 2 | :description: Calculate detailed download stats and generate HTML and badges for PyPI packages 3 | 4 | .. include:: ../../README.rst 5 | 6 | Contents 7 | ========= 8 | 9 | .. toctree:: 10 | :maxdepth: 4 11 | 12 | Example Output 13 | API 14 | Changelog 15 | 16 | Indices and tables 17 | ================== 18 | 19 | * :ref:`genindex` 20 | * :ref:`modindex` 21 | * :ref:`search` 22 | 23 | License 24 | -------- 25 | 26 | pypi-download-stats is licensed under the `GNU Affero General Public License, version 3 or later `_. 27 | This shouldn't be much of a concern to most people. 28 | -------------------------------------------------------------------------------- /docs/source/modules.rst: -------------------------------------------------------------------------------- 1 | pypi_download_stats 2 | =================== 3 | 4 | .. toctree:: 5 | :maxdepth: 4 6 | 7 | pypi_download_stats 8 | -------------------------------------------------------------------------------- /docs/source/pypi_download_stats.dataquery.rst: -------------------------------------------------------------------------------- 1 | pypi\_download\_stats.dataquery module 2 | ====================================== 3 | 4 | .. automodule:: pypi_download_stats.dataquery 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /docs/source/pypi_download_stats.diskdatacache.rst: -------------------------------------------------------------------------------- 1 | pypi\_download\_stats.diskdatacache module 2 | ========================================== 3 | 4 | .. automodule:: pypi_download_stats.diskdatacache 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /docs/source/pypi_download_stats.graphs.rst: -------------------------------------------------------------------------------- 1 | pypi\_download\_stats.graphs module 2 | =================================== 3 | 4 | .. automodule:: pypi_download_stats.graphs 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /docs/source/pypi_download_stats.outputgenerator.rst: -------------------------------------------------------------------------------- 1 | pypi\_download\_stats.outputgenerator module 2 | ============================================ 3 | 4 | .. automodule:: pypi_download_stats.outputgenerator 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /docs/source/pypi_download_stats.projectstats.rst: -------------------------------------------------------------------------------- 1 | pypi\_download\_stats.projectstats module 2 | ========================================= 3 | 4 | .. automodule:: pypi_download_stats.projectstats 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /docs/source/pypi_download_stats.rst: -------------------------------------------------------------------------------- 1 | pypi\_download\_stats package 2 | ============================= 3 | 4 | .. automodule:: pypi_download_stats 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | 9 | Submodules 10 | ---------- 11 | 12 | .. toctree:: 13 | 14 | pypi_download_stats.dataquery 15 | pypi_download_stats.diskdatacache 16 | pypi_download_stats.graphs 17 | pypi_download_stats.outputgenerator 18 | pypi_download_stats.projectstats 19 | pypi_download_stats.runner 20 | pypi_download_stats.version 21 | 22 | -------------------------------------------------------------------------------- /docs/source/pypi_download_stats.runner.rst: -------------------------------------------------------------------------------- 1 | pypi\_download\_stats.runner module 2 | =================================== 3 | 4 | .. automodule:: pypi_download_stats.runner 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /docs/source/pypi_download_stats.version.rst: -------------------------------------------------------------------------------- 1 | pypi\_download\_stats.version module 2 | ==================================== 3 | 4 | .. automodule:: pypi_download_stats.version 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | -------------------------------------------------------------------------------- /pypi_download_stats/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | The latest version of this package is available at: 3 | 4 | 5 | ################################################################################## 6 | Copyright 2016 Jason Antman 7 | 8 | This file is part of pypi-download-stats, also known as pypi-download-stats. 9 | 10 | pypi-download-stats is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU Affero General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | pypi-download-stats is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU Affero General Public License for more details. 19 | 20 | You should have received a copy of the GNU Affero General Public License 21 | along with pypi-download-stats. If not, see . 22 | 23 | The Copyright and Authors attributions contained herein may not be removed or 24 | otherwise altered, except to add the Author attribution of a contributor to 25 | this work. (Additional Terms pursuant to Section 7b of the AGPL v3) 26 | ################################################################################## 27 | While not legally required, I sincerely request that anyone who finds 28 | bugs please submit them at or 29 | to me via email, and that you send any contributions or improvements 30 | either as a pull request on GitHub, or to me via email. 31 | ################################################################################## 32 | 33 | AUTHORS: 34 | Jason Antman 35 | ################################################################################## 36 | """ 37 | -------------------------------------------------------------------------------- /pypi_download_stats/dataquery.py: -------------------------------------------------------------------------------- 1 | """ 2 | The latest version of this package is available at: 3 | 4 | 5 | ################################################################################## 6 | Copyright 2016 Jason Antman 7 | 8 | This file is part of pypi-download-stats, also known as pypi-download-stats. 9 | 10 | pypi-download-stats is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU Affero General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | pypi-download-stats is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU Affero General Public License for more details. 19 | 20 | You should have received a copy of the GNU Affero General Public License 21 | along with pypi-download-stats. If not, see . 22 | 23 | The Copyright and Authors attributions contained herein may not be removed or 24 | otherwise altered, except to add the Author attribution of a contributor to 25 | this work. (Additional Terms pursuant to Section 7b of the AGPL v3) 26 | ################################################################################## 27 | While not legally required, I sincerely request that anyone who finds 28 | bugs please submit them at or 29 | to me via email, and that you send any contributions or improvements 30 | either as a pull request on GitHub, or to me via email. 31 | ################################################################################## 32 | 33 | AUTHORS: 34 | Jason Antman 35 | ################################################################################## 36 | """ 37 | 38 | import logging 39 | import re 40 | import os 41 | import json 42 | from datetime import datetime, timedelta 43 | 44 | from googleapiclient.discovery import build 45 | from googleapiclient.errors import HttpError 46 | from oauth2client.client import GoogleCredentials 47 | 48 | logger = logging.getLogger(__name__) 49 | 50 | 51 | class DataQuery(object): 52 | 53 | _PROJECT_ID = 'the-psf' 54 | _DATASET_ID = 'pypi' 55 | _table_re = re.compile(r'^downloads([0-9]{8})$') 56 | 57 | def __init__(self, project_id, project_names, cache_instance): 58 | """ 59 | Initialize the class to query BigQuery data for the specified projects. 60 | 61 | :param project_id: the Project ID for the user you're authenticating as; 62 | if omitted will attempt to find this in the JSON file at the path 63 | specified by the ``GOOGLE_APPLICATION_CREDENTIALS`` environment 64 | variable. 65 | :type project_id: str 66 | :param project_names: list of string project names to query for 67 | :type project_names: ``list`` 68 | :param cache_instance: DataCache instance 69 | :type cache_instance: :py:class:`~.DiskDataCache` 70 | """ 71 | logger.info('Initializing DataQuery for projects: %s', 72 | ', '.join(project_names)) 73 | self.project_id = project_id 74 | if project_id is None: 75 | self.project_id = self._get_project_id() 76 | logger.debug('project_id to run queries from: %s', self.project_id) 77 | self.cache = cache_instance 78 | self.projects = project_names 79 | self.service = self._get_bigquery_service() 80 | 81 | def _dict_for_projects(self): 82 | """ 83 | Return a dict whose keys are each project name we're querying for, and 84 | values are empty dicts. 85 | 86 | :return: dict with project name keys and empty dict values 87 | :rtype: dict 88 | """ 89 | d = {} 90 | for p in self.projects: 91 | d[p] = {} 92 | return d 93 | 94 | def _get_project_id(self): 95 | """ 96 | Get our projectId from the ``GOOGLE_APPLICATION_CREDENTIALS`` creds 97 | JSON file. 98 | 99 | :return: project ID 100 | :rtype: str 101 | """ 102 | fpath = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', None) 103 | if fpath is None: 104 | raise Exception('ERROR: No project ID specified, and ' 105 | 'GOOGLE_APPLICATION_CREDENTIALS env var is not set') 106 | fpath = os.path.abspath(os.path.expanduser(fpath)) 107 | logger.debug('Reading credentials file at %s to get project_id', fpath) 108 | with open(fpath, 'r') as fh: 109 | cred_data = json.loads(fh.read()) 110 | return cred_data['project_id'] 111 | 112 | def _get_bigquery_service(self): 113 | """ 114 | Connect to the BigQuery service. 115 | 116 | Calling ``GoogleCredentials.get_application_default`` requires that 117 | you either be running in the Google Cloud, or have the 118 | ``GOOGLE_APPLICATION_CREDENTIALS`` environment variable set to the path 119 | to a credentials JSON file. 120 | 121 | :return: authenticated BigQuery service connection object 122 | :rtype: `googleapiclient.discovery.Resource `_ 125 | """ 126 | logger.debug('Getting Google Credentials') 127 | credentials = GoogleCredentials.get_application_default() 128 | logger.debug('Building BigQuery service instance') 129 | bigquery_service = build('bigquery', 'v2', credentials=credentials) 130 | return bigquery_service 131 | 132 | def _get_download_table_ids(self): 133 | """ 134 | Get a list of PyPI downloads table (sharded per day) IDs. 135 | 136 | :return: list of table names (strings) 137 | :rtype: ``list`` 138 | """ 139 | all_table_names = [] # matching per-date table names 140 | logger.info('Querying for all tables in dataset') 141 | tables = self.service.tables() 142 | request = tables.list(projectId=self._PROJECT_ID, 143 | datasetId=self._DATASET_ID) 144 | while request is not None: 145 | response = request.execute() 146 | # if the number of results is evenly divisible by the page size, 147 | # we may end up with a last response that has no 'tables' key, 148 | # and is empty. 149 | if 'tables' not in response: 150 | response['tables'] = [] 151 | for table in response['tables']: 152 | if table['type'] != 'TABLE': 153 | logger.debug('Skipping %s (type=%s)', 154 | table['tableReference']['tableId'], 155 | table['type']) 156 | continue 157 | if not self._table_re.match(table['tableReference']['tableId']): 158 | logger.debug('Skipping table with non-matching name: %s', 159 | table['tableReference']['tableId']) 160 | continue 161 | all_table_names.append(table['tableReference']['tableId']) 162 | request = tables.list_next(previous_request=request, 163 | previous_response=response) 164 | return sorted(all_table_names) 165 | 166 | def _datetime_for_table_name(self, table_name): 167 | """ 168 | Return a :py:class:`datetime.datetime` object for the date of the 169 | data in the specified table name. 170 | 171 | :param table_name: name of the table 172 | :type table_name: str 173 | :return: datetime that the table holds data for 174 | :rtype: datetime.datetime 175 | """ 176 | m = self._table_re.match(table_name) 177 | dt = datetime.strptime(m.group(1), '%Y%m%d') 178 | return dt 179 | 180 | def _table_name_for_datetime(self, dt): 181 | """ 182 | Return the table name for a given datetime. 183 | 184 | :param dt: datetime to get table name for 185 | :type dt: datetime.datetime 186 | :return: table name 187 | :rtype: str 188 | """ 189 | return 'downloads%s' % dt.strftime('%Y%m%d') 190 | 191 | def _run_query(self, query): 192 | """ 193 | Run one query against BigQuery and return the result. 194 | 195 | :param query: the query to run 196 | :type query: str 197 | :return: list of per-row response dicts (key => value) 198 | :rtype: ``list`` 199 | """ 200 | query_request = self.service.jobs() 201 | logger.debug('Running query: %s', query) 202 | start = datetime.now() 203 | resp = query_request.query( 204 | projectId=self.project_id, body={'query': query} 205 | ).execute() 206 | duration = datetime.now() - start 207 | logger.debug('Query response (in %s): %s', duration, resp) 208 | if not resp['jobComplete']: 209 | logger.error('Error: query reported job not complete!') 210 | if int(resp['totalRows']) == 0: 211 | return [] 212 | if int(resp['totalRows']) != len(resp['rows']): 213 | logger.error('Error: query reported %s total rows, but only ' 214 | 'returned %d', resp['totalRows'], len(resp['rows'])) 215 | data = [] 216 | fields = [f['name'] for f in resp['schema']['fields']] 217 | for row in resp['rows']: 218 | d = {} 219 | for idx, val in enumerate(row['f']): 220 | d[fields[idx]] = val['v'] 221 | data.append(d) 222 | return data 223 | 224 | def _from_for_table(self, table_name): 225 | """ 226 | Construct a FROM clause for the specified table name. 227 | 228 | :param table_name: name of the table to select data FROM 229 | :type table_name: str 230 | :return: BigQuery FROM clause 231 | :rtype: str 232 | """ 233 | return 'FROM [%s:%s.%s]' % ( 234 | self._PROJECT_ID, self._DATASET_ID, table_name 235 | ) 236 | 237 | @property 238 | def _where_for_projects(self): 239 | """ 240 | Construct a WHERE clause for the project names we're querying for. 241 | 242 | :return: BigQuery WHERE clause for specified project names 243 | :rtype: str 244 | """ 245 | stmts = ["file.project = '%s'" % p for p in self.projects] 246 | return "WHERE (%s)" % ' OR '.join(stmts) 247 | 248 | def _get_newest_ts_in_table(self, table_name): 249 | """ 250 | Return the timestamp for the newest record in the given table. 251 | 252 | :param table_name: name of the table to query 253 | :type table_name: str 254 | :return: timestamp of newest row in table 255 | :rtype: int 256 | """ 257 | logger.debug( 258 | 'Querying for newest timestamp in table %s', table_name 259 | ) 260 | q = "SELECT TIMESTAMP_TO_SEC(MAX(timestamp)) AS max_ts %s;" % ( 261 | self._from_for_table(table_name) 262 | ) 263 | res = self._run_query(q) 264 | ts = int(res[0]['max_ts']) 265 | logger.debug('Newest timestamp in table %s: %s', table_name, ts) 266 | return ts 267 | 268 | def _query_by_version(self, table_name): 269 | """ 270 | Query for download data broken down by version, for one day. 271 | 272 | :param table_name: table name to query against 273 | :type table_name: str 274 | :return: dict of download information by version; keys are project 275 | name, values are a dict of version to download count 276 | :rtype: dict 277 | """ 278 | logger.info('Querying for downloads by version in table %s', 279 | table_name) 280 | q = "SELECT file.project, file.version, COUNT(*) as dl_count " \ 281 | "%s " \ 282 | "%s " \ 283 | "GROUP BY file.project, file.version;" % ( 284 | self._from_for_table(table_name), 285 | self._where_for_projects 286 | ) 287 | res = self._run_query(q) 288 | result = self._dict_for_projects() 289 | for row in res: 290 | result[row['file_project']][row['file_version']] = int( 291 | row['dl_count']) 292 | return result 293 | 294 | def _query_by_file_type(self, table_name): 295 | """ 296 | Query for download data broken down by file type, for one day. 297 | 298 | :param table_name: table name to query against 299 | :type table_name: str 300 | :return: dict of download information by file type; keys are project 301 | name, values are a dict of file type to download count 302 | :rtype: dict 303 | """ 304 | logger.info('Querying for downloads by file type in table %s', 305 | table_name) 306 | q = "SELECT file.project, file.type, COUNT(*) as dl_count " \ 307 | "%s " \ 308 | "%s " \ 309 | "GROUP BY file.project, file.type;" % ( 310 | self._from_for_table(table_name), 311 | self._where_for_projects 312 | ) 313 | res = self._run_query(q) 314 | result = self._dict_for_projects() 315 | for row in res: 316 | result[row['file_project']][row['file_type']] = int( 317 | row['dl_count']) 318 | return result 319 | 320 | def _query_by_installer(self, table_name): 321 | """ 322 | Query for download data broken down by installer, for one day. 323 | 324 | :param table_name: table name to query against 325 | :type table_name: str 326 | :return: dict of download information by installer; keys are project 327 | name, values are a dict of installer names to dicts of installer 328 | version to download count. 329 | :rtype: dict 330 | """ 331 | logger.info('Querying for downloads by installer in table %s', 332 | table_name) 333 | q = "SELECT file.project, details.installer.name, " \ 334 | "details.installer.version, COUNT(*) as dl_count " \ 335 | "%s " \ 336 | "%s " \ 337 | "GROUP BY file.project, details.installer.name, " \ 338 | "details.installer.version;" % ( 339 | self._from_for_table(table_name), 340 | self._where_for_projects 341 | ) 342 | res = self._run_query(q) 343 | result = self._dict_for_projects() 344 | # iterate through results 345 | for row in res: 346 | # pointer to the per-project result dict 347 | proj = result[row['file_project']] 348 | # grab the name and version; change None to 'unknown' 349 | iname = row['details_installer_name'] 350 | iver = row['details_installer_version'] 351 | if iname not in proj: 352 | proj[iname] = {} 353 | if iver not in proj[iname]: 354 | proj[iname][iver] = 0 355 | proj[iname][iver] += int(row['dl_count']) 356 | return result 357 | 358 | def _query_by_implementation(self, table_name): 359 | """ 360 | Query for download data broken down by Python implementation, for one 361 | day. 362 | 363 | :param table_name: table name to query against 364 | :type table_name: str 365 | :return: dict of download information by implementation; keys are 366 | project name, values are a dict of implementation names to dicts of 367 | implementation version to download count. 368 | :rtype: dict 369 | """ 370 | logger.info('Querying for downloads by Python implementation in table ' 371 | '%s', table_name) 372 | q = "SELECT file.project, details.implementation.name, " \ 373 | "details.implementation.version, COUNT(*) as dl_count " \ 374 | "%s " \ 375 | "%s " \ 376 | "GROUP BY file.project, details.implementation.name, " \ 377 | "details.implementation.version;" % ( 378 | self._from_for_table(table_name), 379 | self._where_for_projects 380 | ) 381 | res = self._run_query(q) 382 | result = self._dict_for_projects() 383 | # iterate through results 384 | for row in res: 385 | # pointer to the per-project result dict 386 | proj = result[row['file_project']] 387 | # grab the name and version; change None to 'unknown' 388 | iname = row['details_implementation_name'] 389 | iver = row['details_implementation_version'] 390 | if iname not in proj: 391 | proj[iname] = {} 392 | if iver not in proj[iname]: 393 | proj[iname][iver] = 0 394 | proj[iname][iver] += int(row['dl_count']) 395 | return result 396 | 397 | def _query_by_system(self, table_name): 398 | """ 399 | Query for download data broken down by system, for one day. 400 | 401 | :param table_name: table name to query against 402 | :type table_name: str 403 | :return: dict of download information by system; keys are project name, 404 | values are a dict of system names to download count. 405 | :rtype: dict 406 | """ 407 | logger.info('Querying for downloads by system in table %s', 408 | table_name) 409 | q = "SELECT file.project, details.system.name, COUNT(*) as dl_count " \ 410 | "%s " \ 411 | "%s " \ 412 | "GROUP BY file.project, details.system.name;" % ( 413 | self._from_for_table(table_name), 414 | self._where_for_projects 415 | ) 416 | res = self._run_query(q) 417 | result = self._dict_for_projects() 418 | for row in res: 419 | system = row['details_system_name'] 420 | result[row['file_project']][system] = int( 421 | row['dl_count']) 422 | return result 423 | 424 | def _query_by_distro(self, table_name): 425 | """ 426 | Query for download data broken down by OS distribution, for one day. 427 | 428 | :param table_name: table name to query against 429 | :type table_name: str 430 | :return: dict of download information by distro; keys are project name, 431 | values are a dict of distro names to dicts of distro version to 432 | download count. 433 | :rtype: dict 434 | """ 435 | logger.info('Querying for downloads by distro in table %s', table_name) 436 | q = "SELECT file.project, details.distro.name, " \ 437 | "details.distro.version, COUNT(*) as dl_count " \ 438 | "%s " \ 439 | "%s " \ 440 | "GROUP BY file.project, details.distro.name, " \ 441 | "details.distro.version;" % ( 442 | self._from_for_table(table_name), 443 | self._where_for_projects 444 | ) 445 | res = self._run_query(q) 446 | result = self._dict_for_projects() 447 | # iterate through results 448 | for row in res: 449 | # pointer to the per-project result dict 450 | proj = result[row['file_project']] 451 | # grab the name and version; change None to 'unknown' 452 | dname = row['details_distro_name'] 453 | dver = row['details_distro_version'] 454 | if dname not in proj: 455 | proj[dname] = {} 456 | if dver not in proj[dname]: 457 | proj[dname][dver] = 0 458 | proj[dname][dver] += int(row['dl_count']) 459 | return result 460 | 461 | def _query_by_country_code(self, table_name): 462 | """ 463 | Query for download data broken down by country code, for one day. 464 | 465 | :param table_name: table name to query against 466 | :type table_name: str 467 | :return: dict of download information by country code; keys are project 468 | name, values are a dict of country code to download count. 469 | :rtype: dict 470 | """ 471 | logger.info('Querying for downloads by country code in table %s', 472 | table_name) 473 | q = "SELECT file.project, country_code, COUNT(*) as dl_count " \ 474 | "%s " \ 475 | "%s " \ 476 | "GROUP BY file.project, country_code;" % ( 477 | self._from_for_table(table_name), 478 | self._where_for_projects 479 | ) 480 | res = self._run_query(q) 481 | result = self._dict_for_projects() 482 | for row in res: 483 | result[row['file_project']][row['country_code']] = int( 484 | row['dl_count']) 485 | return result 486 | 487 | def query_one_table(self, table_name): 488 | """ 489 | Run all queries for the given table name (date) and update the cache. 490 | 491 | :param table_name: table name to query against 492 | :type table_name: str 493 | """ 494 | table_date = self._datetime_for_table_name(table_name) 495 | logger.info('Running all queries for date table: %s (%s)', table_name, 496 | table_date.strftime('%Y-%m-%d')) 497 | final = self._dict_for_projects() 498 | try: 499 | data_timestamp = self._get_newest_ts_in_table(table_name) 500 | except HttpError as exc: 501 | try: 502 | content = json.loads(exc.content.decode('utf-8')) 503 | if content['error']['message'].startswith('Not found: Table'): 504 | logger.error("Table %s not found; no data for that day", 505 | table_name) 506 | return 507 | except: 508 | pass 509 | raise exc 510 | # data queries 511 | # note - ProjectStats._is_empty_cache_record() needs to know keys 512 | for name, func in { 513 | 'by_version': self._query_by_version, 514 | 'by_file_type': self._query_by_file_type, 515 | 'by_installer': self._query_by_installer, 516 | 'by_implementation': self._query_by_implementation, 517 | 'by_system': self._query_by_system, 518 | 'by_distro': self._query_by_distro, 519 | 'by_country': self._query_by_country_code 520 | }.items(): 521 | tmp = func(table_name) 522 | for proj_name in tmp: 523 | final[proj_name][name] = tmp[proj_name] 524 | # add to cache 525 | for proj_name in final: 526 | self.cache.set(proj_name, table_date, final[proj_name], 527 | data_timestamp) 528 | 529 | def _have_cache_for_date(self, dt): 530 | """ 531 | Return True if we have cached data for all projects for the specified 532 | datetime. Return False otherwise. 533 | 534 | :param dt: datetime to find cache for 535 | :type dt: datetime.datetime 536 | :return: True if we have cache for all projects for this date, False 537 | otherwise 538 | :rtype: bool 539 | """ 540 | for p in self.projects: 541 | if self.cache.get(p, dt) is None: 542 | return False 543 | return True 544 | 545 | def backfill_history(self, num_days, available_table_names): 546 | """ 547 | Backfill historical data for days that are missing. 548 | 549 | :param num_days: number of days of historical data to backfill, 550 | if missing 551 | :type num_days: int 552 | :param available_table_names: names of available per-date tables 553 | :type available_table_names: ``list`` 554 | """ 555 | if num_days == -1: 556 | # skip the first date, under the assumption that data may be 557 | # incomplete 558 | logger.info('Backfilling all available history') 559 | start_table = available_table_names[1] 560 | else: 561 | logger.info('Backfilling %d days of history', num_days) 562 | start_table = available_table_names[-1 * num_days] 563 | start_date = self._datetime_for_table_name(start_table) 564 | end_table = available_table_names[-3] 565 | end_date = self._datetime_for_table_name(end_table) 566 | logger.debug( 567 | 'Backfilling history from %s (%s) to %s (%s)', start_table, 568 | start_date.strftime('%Y-%m-%d'), end_table, 569 | end_date.strftime('%Y-%m-%d') 570 | ) 571 | for days in range((end_date - start_date).days + 1): 572 | backfill_dt = start_date + timedelta(days=days) 573 | if self._have_cache_for_date(backfill_dt): 574 | logger.info('Cache present for all projects for %s; skipping', 575 | backfill_dt.strftime('%Y-%m-%d')) 576 | continue 577 | backfill_table = self._table_name_for_datetime(backfill_dt) 578 | logger.info('Backfilling %s (%s)', backfill_table, 579 | backfill_dt.strftime('%Y-%m-%d')) 580 | self.query_one_table(backfill_table) 581 | 582 | def run_queries(self, backfill_num_days=7): 583 | """ 584 | Run the data queries for the specified projects. 585 | 586 | :param backfill_num_days: number of days of historical data to backfill, 587 | if missing 588 | :type backfill_num_days: int 589 | """ 590 | available_tables = self._get_download_table_ids() 591 | logger.debug('Found %d available download tables: %s', 592 | len(available_tables), available_tables) 593 | today_table = available_tables[-1] 594 | yesterday_table = available_tables[-2] 595 | self.query_one_table(today_table) 596 | self.query_one_table(yesterday_table) 597 | self.backfill_history(backfill_num_days, available_tables) 598 | -------------------------------------------------------------------------------- /pypi_download_stats/diskdatacache.py: -------------------------------------------------------------------------------- 1 | """ 2 | The latest version of this package is available at: 3 | 4 | 5 | ################################################################################## 6 | Copyright 2016 Jason Antman 7 | 8 | This file is part of pypi-download-stats, also known as pypi-download-stats. 9 | 10 | pypi-download-stats is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU Affero General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | pypi-download-stats is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU Affero General Public License for more details. 19 | 20 | You should have received a copy of the GNU Affero General Public License 21 | along with pypi-download-stats. If not, see . 22 | 23 | The Copyright and Authors attributions contained herein may not be removed or 24 | otherwise altered, except to add the Author attribution of a contributor to 25 | this work. (Additional Terms pursuant to Section 7b of the AGPL v3) 26 | ################################################################################## 27 | While not legally required, I sincerely request that anyone who finds 28 | bugs please submit them at or 29 | to me via email, and that you send any contributions or improvements 30 | either as a pull request on GitHub, or to me via email. 31 | ################################################################################## 32 | 33 | AUTHORS: 34 | Jason Antman 35 | ################################################################################## 36 | """ 37 | 38 | import logging 39 | import os 40 | import json 41 | import re 42 | from datetime import datetime 43 | import time 44 | 45 | from pypi_download_stats.version import VERSION 46 | 47 | logger = logging.getLogger(__name__) 48 | 49 | 50 | class DiskDataCache(object): 51 | 52 | def __init__(self, cache_path): 53 | """ 54 | Initialize the disk data cache. 55 | 56 | :param cache_path: absolute path to the cache directory 57 | :type cache_path: str 58 | """ 59 | cache_path = os.path.abspath(os.path.expanduser(cache_path)) 60 | if not os.path.exists(cache_path): 61 | logger.debug('Creating cache directory: %s', cache_path) 62 | os.makedirs(cache_path) 63 | logger.info('Initialized DiskDataCache cache_path=%s', cache_path) 64 | self.cache_path = cache_path 65 | 66 | def _path_for_file(self, project_name, date): 67 | """ 68 | Generate the path on disk for a specified project and date. 69 | 70 | :param project_name: the PyPI project name for the data 71 | :type project: str 72 | :param date: the date for the data 73 | :type date: datetime.datetime 74 | :return: path for where to store this data on disk 75 | :rtype: str 76 | """ 77 | return os.path.join( 78 | self.cache_path, 79 | '%s_%s.json' % (project_name, date.strftime('%Y%m%d')) 80 | ) 81 | 82 | def get(self, project, date): 83 | """ 84 | Get the cache data for a specified project for the specified date. 85 | Returns None if the data cannot be found in the cache. 86 | 87 | :param project: PyPi project name to get data for 88 | :type project: str 89 | :param date: date to get data for 90 | :type date: datetime.datetime 91 | :return: dict of per-date data for project 92 | :rtype: :py:obj:`dict` or ``None`` 93 | """ 94 | fpath = self._path_for_file(project, date) 95 | logger.debug('Cache GET project=%s date=%s - path=%s', 96 | project, date.strftime('%Y-%m-%d'), fpath) 97 | try: 98 | with open(fpath, 'r') as fh: 99 | data = json.loads(fh.read()) 100 | except: 101 | logger.debug('Error getting from cache for project=%s date=%s', 102 | project, date.strftime('%Y-%m-%d')) 103 | return None 104 | data['cache_metadata']['date'] = datetime.strptime( 105 | data['cache_metadata']['date'], 106 | '%Y%m%d' 107 | ) 108 | data['cache_metadata']['updated'] = datetime.fromtimestamp( 109 | data['cache_metadata']['updated'] 110 | ) 111 | return data 112 | 113 | def set(self, project, date, data, data_ts): 114 | """ 115 | Set the cache data for a specified project for the specified date. 116 | 117 | :param project: project name to set data for 118 | :type project: str 119 | :param date: date to set data for 120 | :type date: datetime.datetime 121 | :param data: data to cache 122 | :type data: dict 123 | :param data_ts: maximum timestamp in the BigQuery data table 124 | :type data_ts: int 125 | """ 126 | data['cache_metadata'] = { 127 | 'project': project, 128 | 'date': date.strftime('%Y%m%d'), 129 | 'updated': time.time(), 130 | 'version': VERSION, 131 | 'data_ts': data_ts 132 | } 133 | fpath = self._path_for_file(project, date) 134 | logger.debug('Cache SET project=%s date=%s - path=%s', 135 | project, date.strftime('%Y-%m-%d'), fpath) 136 | with open(fpath, 'w') as fh: 137 | fh.write(json.dumps(data)) 138 | 139 | def get_dates_for_project(self, project): 140 | """ 141 | Return a list of the dates we have in cache for the specified project, 142 | sorted in ascending date order. 143 | 144 | :param project: project name 145 | :type project: str 146 | :return: list of datetime.datetime objects 147 | :rtype: datetime.datetime 148 | """ 149 | file_re = re.compile(r'^%s_([0-9]{8})\.json$' % project) 150 | all_dates = [] 151 | for f in os.listdir(self.cache_path): 152 | if not os.path.isfile(os.path.join(self.cache_path, f)): 153 | continue 154 | m = file_re.match(f) 155 | if m is None: 156 | continue 157 | all_dates.append(datetime.strptime(m.group(1), '%Y%m%d')) 158 | return sorted(all_dates) 159 | -------------------------------------------------------------------------------- /pypi_download_stats/graphs.py: -------------------------------------------------------------------------------- 1 | """ 2 | The latest version of this package is available at: 3 | 4 | 5 | ################################################################################## 6 | Copyright 2016 Jason Antman 7 | 8 | This file is part of pypi-download-stats, also known as pypi-download-stats. 9 | 10 | pypi-download-stats is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU Affero General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | pypi-download-stats is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU Affero General Public License for more details. 19 | 20 | You should have received a copy of the GNU Affero General Public License 21 | along with pypi-download-stats. If not, see . 22 | 23 | The Copyright and Authors attributions contained herein may not be removed or 24 | otherwise altered, except to add the Author attribution of a contributor to 25 | this work. (Additional Terms pursuant to Section 7b of the AGPL v3) 26 | ################################################################################## 27 | While not legally required, I sincerely request that anyone who finds 28 | bugs please submit them at or 29 | to me via email, and that you send any contributions or improvements 30 | either as a pull request on GitHub, or to me via email. 31 | ################################################################################## 32 | 33 | AUTHORS: 34 | Jason Antman 35 | ################################################################################## 36 | """ 37 | 38 | import logging 39 | from datetime import datetime 40 | from copy import deepcopy 41 | 42 | from bokeh.charts import Area 43 | from bokeh.models import (PanTool, BoxZoomTool, WheelZoomTool, SaveTool, 44 | ResetTool, ResizeTool, HoverTool, GlyphRenderer) 45 | from bokeh.models.annotations import Legend 46 | from bokeh.plotting import ColumnDataSource 47 | from bokeh.models.glyphs import Line, Patches 48 | from bokeh.embed import components 49 | 50 | logger = logging.getLogger(__name__) 51 | 52 | 53 | class FancyAreaGraph(object): 54 | """ 55 | Wrapper around bokeh.charts.Area to make it look and work nicer. 56 | """ 57 | 58 | def __init__(self, identifier, title, data, labels, y_name): 59 | """ 60 | Initialize a wrapper around :py:class:`bokeh.charts.Area` that handles 61 | our data format, makes it look nice, and makes 62 | :py:class:`bokeh.models.HoverTool` work right with a stacked Area chart. 63 | 64 | :param identifier: URL-safe graph identifier 65 | :type identifier: str 66 | :param title: Human-readable graph title 67 | :type title: str 68 | :param data: dictionary of data; keys are series names, values are lists 69 | of download counts 70 | :type data: dict 71 | :param labels: X-axis labels (dates), :py:class:`datetime.datetime` 72 | :type labels: list 73 | :param y_name: tooltip name for Y data series 74 | :type y_name: str 75 | """ 76 | logger.debug('Initializing graph for %s ("%s")', identifier, title) 77 | self._graph_id = identifier 78 | self._title = title 79 | self._data = data 80 | self._labels = labels 81 | self._y_series_names = [k for k in data.keys()] 82 | self._y_name = y_name 83 | # Date elements - x axis keys 84 | self._data['Date'] = labels 85 | # FmtDate elements - and HoverTool text 86 | self._data['FmtDate'] = [x.strftime('%Y-%m-%d') for x in labels] 87 | 88 | def generate_graph(self): 89 | """ 90 | Generate the graph; return a 2-tuple of strings, script to place in the 91 | head of the HTML document and div content for the graph itself. 92 | 93 | :return: 2-tuple (script, div) 94 | :rtype: tuple 95 | """ 96 | logger.debug('Generating graph for %s', self._graph_id) 97 | # tools to use 98 | tools = [ 99 | PanTool(), 100 | BoxZoomTool(), 101 | WheelZoomTool(), 102 | SaveTool(), 103 | ResetTool(), 104 | ResizeTool() 105 | ] 106 | 107 | # generate the stacked area graph 108 | try: 109 | g = Area( 110 | self._data, x='Date', y=self._y_series_names, 111 | title=self._title, stack=True, xlabel='Date', 112 | ylabel='Downloads', tools=tools, 113 | # note the width and height will be set by JavaScript 114 | plot_height=400, plot_width=800, 115 | toolbar_location='above', legend=False 116 | ) 117 | except Exception as ex: 118 | logger.error("Error generating %s graph", self._graph_id) 119 | logger.error("Data: %s", self._data) 120 | logger.error("y=%s", self._y_series_names) 121 | raise ex 122 | 123 | lines = [] 124 | legend_parts = [] 125 | # add a line at the top of each Patch (stacked area) for hovertool 126 | for renderer in g.select(GlyphRenderer): 127 | if not isinstance(renderer.glyph, Patches): 128 | continue 129 | series_name = renderer.data_source.data['series'][0] 130 | logger.debug('Adding line for Patches %s (series: %s)', renderer, 131 | series_name) 132 | line = self._line_for_patches(self._data, g, renderer, series_name) 133 | if line is not None: 134 | lines.append(line) 135 | legend_parts.append((series_name, [line])) 136 | 137 | # add the Hovertool, specifying only our line glyphs 138 | g.add_tools( 139 | HoverTool( 140 | tooltips=[ 141 | (self._y_name, '@SeriesName'), 142 | ('Date', '@FmtDate'), 143 | ('Downloads', '@Downloads'), 144 | ], 145 | renderers=lines, 146 | line_policy='nearest' 147 | ) 148 | ) 149 | 150 | # legend outside chart area 151 | legend = Legend(legends=legend_parts, location=(0, 0)) 152 | g.add_layout(legend, 'right') 153 | return components(g) 154 | 155 | def _line_for_patches(self, data, chart, renderer, series_name): 156 | """ 157 | Add a line along the top edge of a Patch in a stacked Area Chart; return 158 | the new Glyph for addition to HoverTool. 159 | 160 | :param data: original data for the graph 161 | :type data: dict 162 | :param chart: Chart to add the line to 163 | :type chart: bokeh.charts.Chart 164 | :param renderer: GlyphRenderer containing one Patches glyph, to draw 165 | the line for 166 | :type renderer: bokeh.models.renderers.GlyphRenderer 167 | :param series_name: the data series name this Patches represents 168 | :type series_name: str 169 | :return: GlyphRenderer for a Line at the top edge of this Patch 170 | :rtype: bokeh.models.renderers.GlyphRenderer 171 | """ 172 | # @TODO this method needs a major refactor 173 | # get the original x and y values, and color 174 | xvals = deepcopy(renderer.data_source.data['x_values'][0]) 175 | yvals = deepcopy(renderer.data_source.data['y_values'][0]) 176 | line_color = renderer.glyph.fill_color 177 | 178 | # save original values for logging if needed 179 | orig_xvals = [x for x in xvals] 180 | orig_yvals = [y for y in yvals] 181 | 182 | # get a list of the values 183 | new_xvals = [x for x in xvals] 184 | new_yvals = [y for y in yvals] 185 | 186 | # so when a Patch is made, the first point is (0,0); trash it 187 | xvals = new_xvals[1:] 188 | yvals = new_yvals[1:] 189 | 190 | # then, we can tell the last point in the "top" line because it will be 191 | # followed by a point with the same x value and a y value of 0. 192 | last_idx = None 193 | for idx, val in enumerate(xvals): 194 | if yvals[idx+1] == 0 and xvals[idx+1] == xvals[idx]: 195 | last_idx = idx 196 | break 197 | 198 | if last_idx is None: 199 | logger.error('Unable to find top line of patch (x_values=%s ' 200 | 'y_values=%s', orig_xvals, orig_yvals) 201 | return None 202 | 203 | # truncate our values to just what makes up the top line 204 | xvals = xvals[:last_idx+1] 205 | yvals = yvals[:last_idx+1] 206 | 207 | # Currently (bokeh 0.12.1) HoverTool won't show the tooltip for the last 208 | # point in our line. As a hack for this, add a point with the same Y 209 | # value and an X slightly before it. 210 | lastx = xvals[-1] 211 | xvals[-1] = lastx - 1000 # 1000 nanoseconds 212 | xvals.append(lastx) 213 | yvals.append(yvals[-1]) 214 | # get the actual download counts from the original data 215 | download_counts = [ 216 | data[series_name][y] for y in range(0, len(yvals) - 1) 217 | ] 218 | download_counts.append(download_counts[-1]) 219 | 220 | # create a ColumnDataSource for the new overlay line 221 | data2 = { 222 | 'x': xvals, # Date/x values are numpy.datetime64 223 | 'y': yvals, 224 | # the following are hacks for data that we want in the HoverTool 225 | # tooltip 226 | 'SeriesName': [series_name for _ in yvals], 227 | # formatted date 228 | 'FmtDate': [self.datetime64_to_formatted_date(x) for x in xvals], 229 | # to show the exact value, not where the pointer is 230 | 'Downloads': download_counts 231 | } 232 | # set the formatted date for our hacked second-to-last point to the 233 | # same value as the last point 234 | data2['FmtDate'][-2] = data2['FmtDate'][-1] 235 | 236 | # create the CloumnDataSource, then the line for it, then the Glyph 237 | line_ds = ColumnDataSource(data2) 238 | line = Line(x='x', y='y', line_color=line_color) 239 | lineglyph = chart.add_glyph(line_ds, line) 240 | return lineglyph 241 | 242 | def datetime64_to_formatted_date(self, dt64): 243 | dt_int = dt64.astype(int) * 1e-9 244 | return datetime.utcfromtimestamp(dt_int).strftime('%Y-%m-%d') 245 | -------------------------------------------------------------------------------- /pypi_download_stats/outputgenerator.py: -------------------------------------------------------------------------------- 1 | """ 2 | The latest version of this package is available at: 3 | 4 | 5 | ################################################################################## 6 | Copyright 2016 Jason Antman 7 | 8 | This file is part of pypi-download-stats, also known as pypi-download-stats. 9 | 10 | pypi-download-stats is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU Affero General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | pypi-download-stats is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU Affero General Public License for more details. 19 | 20 | You should have received a copy of the GNU Affero General Public License 21 | along with pypi-download-stats. If not, see . 22 | 23 | The Copyright and Authors attributions contained herein may not be removed or 24 | otherwise altered, except to add the Author attribution of a contributor to 25 | this work. (Additional Terms pursuant to Section 7b of the AGPL v3) 26 | ################################################################################## 27 | While not legally required, I sincerely request that anyone who finds 28 | bugs please submit them at or 29 | to me via email, and that you send any contributions or improvements 30 | either as a pull request on GitHub, or to me via email. 31 | ################################################################################## 32 | 33 | AUTHORS: 34 | Jason Antman 35 | ################################################################################## 36 | """ 37 | 38 | import logging 39 | import os 40 | import shutil 41 | from platform import node as platform_node 42 | from getpass import getuser 43 | import requests 44 | 45 | from jinja2 import Environment, PackageLoader 46 | from bokeh.resources import Resources 47 | 48 | from .version import VERSION, PROJECT_URL 49 | from .graphs import FancyAreaGraph 50 | 51 | logger = logging.getLogger(__name__) 52 | 53 | 54 | class OutputGenerator(object): 55 | 56 | # this list defines the order in which graphs will show up on the page 57 | GRAPH_KEYS = [ 58 | 'by-version', 59 | 'by-file-type', 60 | 'by-installer', 61 | 'by-implementation', 62 | 'by-system', 63 | 'by-country', 64 | 'by-distro' 65 | ] 66 | 67 | def __init__(self, project_name, stats, output_dir): 68 | """ 69 | Initialize an OutputGenerator for one project. 70 | 71 | :param project_name: name of the project to generate output for 72 | :type project_name: str 73 | :param stats: ProjectStats instance for the project 74 | :type stats: :py:class:`~.ProjectStats`hey 75 | :param output_dir: path to write project output to 76 | :type output_dir: str 77 | """ 78 | logger.debug('Initializing OutputGenerator for project %s ' 79 | '(output_dir=%s)', project_name, output_dir) 80 | self.project_name = project_name 81 | self._stats = stats 82 | self.output_dir = os.path.abspath(os.path.expanduser(output_dir)) 83 | if os.path.exists(self.output_dir): 84 | logger.debug('Removing existing per-project directory: %s', 85 | self.output_dir) 86 | shutil.rmtree(self.output_dir) 87 | logger.debug('Creating per-project output directory: %s', 88 | self.output_dir) 89 | os.makedirs(self.output_dir) 90 | self._graphs = {} 91 | self._badges = {} 92 | 93 | def _generate_html(self): 94 | """ 95 | Generate the HTML for the specified graphs. 96 | 97 | :return: 98 | :rtype: 99 | """ 100 | logger.debug('Generating templated HTML') 101 | env = Environment( 102 | loader=PackageLoader('pypi_download_stats', 'templates'), 103 | extensions=['jinja2.ext.loopcontrols']) 104 | env.filters['format_date_long'] = filter_format_date_long 105 | env.filters['format_date_ymd'] = filter_format_date_ymd 106 | env.filters['data_columns'] = filter_data_columns 107 | template = env.get_template('base.html') 108 | 109 | logger.debug('Rendering template') 110 | html = template.render( 111 | project=self.project_name, 112 | cache_date=self._stats.as_of_datetime, 113 | user=getuser(), 114 | host=platform_node(), 115 | version=VERSION, 116 | proj_url=PROJECT_URL, 117 | graphs=self._graphs, 118 | graph_keys=self.GRAPH_KEYS, 119 | resources=Resources(mode='inline').render(), 120 | badges=self._badges 121 | ) 122 | logger.debug('Template rendered') 123 | return html 124 | 125 | def _data_dict_to_bokeh_chart_data(self, data): 126 | """ 127 | Take a dictionary of data, as returned by the :py:class:`~.ProjectStats` 128 | per_*_data properties, return a 2-tuple of data dict and x labels list 129 | usable by bokeh.charts. 130 | 131 | :param data: data dict from :py:class:`~.ProjectStats` property 132 | :type data: dict 133 | :return: 2-tuple of data dict, x labels list 134 | :rtype: tuple 135 | """ 136 | labels = [] 137 | # find all the data keys 138 | keys = set() 139 | for date in data: 140 | for k in data[date]: 141 | keys.add(k) 142 | # final output dict 143 | out_data = {} 144 | for k in keys: 145 | out_data[k] = [] 146 | # transform the data; deal with sparse data 147 | for data_date, data_dict in sorted(data.items()): 148 | labels.append(data_date) 149 | for k in out_data: 150 | if k in data_dict: 151 | out_data[k].append(data_dict[k]) 152 | else: 153 | out_data[k].append(0) 154 | return out_data, labels 155 | 156 | def _limit_data(self, data): 157 | """ 158 | Find the per-day average of each series in the data over the last 7 159 | days; drop all but the top 10. 160 | 161 | :param data: original graph data 162 | :type data: dict 163 | :return: dict containing only the top 10 series, based on average over 164 | the last 7 days. 165 | :rtype: dict 166 | """ 167 | if len(data.keys()) <= 10: 168 | logger.debug("Data has less than 10 keys; not limiting") 169 | return data 170 | # average last 7 days of each series 171 | avgs = {} 172 | for k in data: 173 | if len(data[k]) <= 7: 174 | vals = data[k] 175 | else: 176 | vals = data[k][-7:] 177 | avgs[k] = sum(vals) / len(vals) 178 | # hold state 179 | final_data = {} # final data dict 180 | other = [] # values for dropped/'other' series 181 | count = 0 # iteration counter 182 | # iterate the sorted averages; either drop or keep 183 | for k in sorted(avgs, key=avgs.get, reverse=True): 184 | if count < 10: 185 | final_data[k] = data[k] 186 | logger.debug("Keeping data series %s (average over last 7 " 187 | "days of data: %d", k, avgs[k]) 188 | else: 189 | logger.debug("Adding data series %s to 'other' (average over " 190 | "last 7 days of data: %d", k, avgs[k]) 191 | other.append(data[k]) 192 | count += 1 193 | # sum up the other data and add to final 194 | final_data['other'] = [sum(series) for series in zip(*other)] 195 | return final_data 196 | 197 | def _generate_graph(self, name, title, stats_data, y_name): 198 | """ 199 | Generate a downloads graph; append it to ``self._graphs``. 200 | 201 | :param name: HTML name of the graph, also used in ``self.GRAPH_KEYS`` 202 | :type name: str 203 | :param title: human-readable title for the graph 204 | :type title: str 205 | :param stats_data: data dict from ``self._stats`` 206 | :type stats_data: dict 207 | :param y_name: Y axis metric name 208 | :type y_name: str 209 | """ 210 | logger.debug('Generating chart data for %s graph', name) 211 | orig_data, labels = self._data_dict_to_bokeh_chart_data(stats_data) 212 | data = self._limit_data(orig_data) 213 | logger.debug('Generating %s graph', name) 214 | script, div = FancyAreaGraph( 215 | name, '%s %s' % (self.project_name, title), data, labels, 216 | y_name).generate_graph() 217 | logger.debug('%s graph generated', name) 218 | self._graphs[name] = { 219 | 'title': title, 220 | 'script': script, 221 | 'div': div, 222 | 'raw_data': stats_data 223 | } 224 | 225 | def _generate_badges(self): 226 | """ 227 | Generate download badges. Append them to ``self._badges``. 228 | """ 229 | daycount = self._stats.downloads_per_day 230 | day = self._generate_badge('Downloads', '%d/day' % daycount) 231 | self._badges['per-day'] = day 232 | weekcount = self._stats.downloads_per_week 233 | if weekcount is None: 234 | # we don't have enough data for week (or month) 235 | return 236 | week = self._generate_badge('Downloads', '%d/week' % weekcount) 237 | self._badges['per-week'] = week 238 | monthcount = self._stats.downloads_per_month 239 | if monthcount is None: 240 | # we don't have enough data for month 241 | return 242 | month = self._generate_badge('Downloads', '%d/month' % monthcount) 243 | self._badges['per-month'] = month 244 | 245 | def _generate_badge(self, subject, status): 246 | """ 247 | Generate SVG for one badge via shields.io. 248 | 249 | :param subject: subject; left-hand side of badge 250 | :type subject: str 251 | :param status: status; right-hand side of badge 252 | :type status: str 253 | :return: badge SVG 254 | :rtype: str 255 | """ 256 | url = 'https://img.shields.io/badge/%s-%s-brightgreen.svg' \ 257 | '?style=flat&maxAge=3600' % (subject, status) 258 | logger.debug("Getting badge for %s => %s (%s)", subject, status, url) 259 | res = requests.get(url) 260 | if res.status_code != 200: 261 | raise Exception("Error: got status %s for shields.io badge: %s", 262 | res.status_code, res.text) 263 | logger.debug('Got %d character response from shields.io', len(res.text)) 264 | return res.text 265 | 266 | def generate(self): 267 | """ 268 | Generate all output types and write to disk. 269 | """ 270 | logger.info('Generating graphs') 271 | self._generate_graph( 272 | 'by-version', 273 | 'Downloads by Version', 274 | self._stats.per_version_data, 275 | 'Version' 276 | ) 277 | self._generate_graph( 278 | 'by-file-type', 279 | 'Downloads by File Type', 280 | self._stats.per_file_type_data, 281 | 'File Type' 282 | ) 283 | self._generate_graph( 284 | 'by-installer', 285 | 'Downloads by Installer', 286 | self._stats.per_installer_data, 287 | 'Installer' 288 | ) 289 | self._generate_graph( 290 | 'by-implementation', 291 | 'Downloads by Python Implementation/Version', 292 | self._stats.per_implementation_data, 293 | 'Implementation/Version' 294 | ) 295 | self._generate_graph( 296 | 'by-system', 297 | 'Downloads by System Type', 298 | self._stats.per_system_data, 299 | 'System' 300 | ) 301 | self._generate_graph( 302 | 'by-country', 303 | 'Downloads by Country', 304 | self._stats.per_country_data, 305 | 'Country' 306 | ) 307 | self._generate_graph( 308 | 'by-distro', 309 | 'Downloads by Distro', 310 | self._stats.per_distro_data, 311 | 'Distro' 312 | ) 313 | self._generate_badges() 314 | logger.info('Generating HTML') 315 | html = self._generate_html() 316 | html_path = os.path.join(self.output_dir, 'index.html') 317 | with open(html_path, 'wb') as fh: 318 | fh.write(html.encode('utf-8')) 319 | logger.info('HTML report written to %s', html_path) 320 | logger.info('Writing SVG badges') 321 | for name, svg in self._badges.items(): 322 | path = os.path.join(self.output_dir, '%s.svg' % name) 323 | with open(path, 'w') as fh: 324 | fh.write(svg) 325 | logger.info('%s badge written to: %s', name, path) 326 | 327 | 328 | def filter_format_date_long(dt): 329 | """ 330 | Format a datetime into a long string 331 | 332 | :param dt: datetime to format 333 | :type dt: datetime.datetime 334 | :returns: long date string 335 | :rtype: str 336 | """ 337 | return dt.strftime('%Y-%m-%d %H:%M:%S%z (%Z)') 338 | 339 | 340 | def filter_format_date_ymd(dt): 341 | """ 342 | Format a datetime into a Y-m-d string 343 | 344 | :param dt: datetime to format 345 | :type dt: datetime.datetime 346 | :returns: Y-m-d date string 347 | :rtype: str 348 | """ 349 | return dt.strftime('%Y-%m-%d') 350 | 351 | 352 | def filter_data_columns(data): 353 | """ 354 | Given a dict of data such as those in :py:class:`~.ProjectStats` attributes, 355 | made up of :py:class:`datetime.datetime` keys and values of dicts of column 356 | keys to counts, return a list of the distinct column keys in sorted order. 357 | 358 | :param data: data dict as returned by ProjectStats attributes 359 | :type data: dict 360 | :return: sorted list of distinct keys 361 | :rtype: ``list`` 362 | """ 363 | keys = set() 364 | for dt, d in data.items(): 365 | for k in d: 366 | keys.add(k) 367 | return sorted([x for x in keys]) 368 | -------------------------------------------------------------------------------- /pypi_download_stats/projectstats.py: -------------------------------------------------------------------------------- 1 | """ 2 | The latest version of this package is available at: 3 | 4 | 5 | ################################################################################## 6 | Copyright 2016 Jason Antman 7 | 8 | This file is part of pypi-download-stats, also known as pypi-download-stats. 9 | 10 | pypi-download-stats is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU Affero General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | pypi-download-stats is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU Affero General Public License for more details. 19 | 20 | You should have received a copy of the GNU Affero General Public License 21 | along with pypi-download-stats. If not, see . 22 | 23 | The Copyright and Authors attributions contained herein may not be removed or 24 | otherwise altered, except to add the Author attribution of a contributor to 25 | this work. (Additional Terms pursuant to Section 7b of the AGPL v3) 26 | ################################################################################## 27 | While not legally required, I sincerely request that anyone who finds 28 | bugs please submit them at or 29 | to me via email, and that you send any contributions or improvements 30 | either as a pull request on GitHub, or to me via email. 31 | ################################################################################## 32 | 33 | AUTHORS: 34 | Jason Antman 35 | ################################################################################## 36 | """ 37 | 38 | import logging 39 | from datetime import datetime, timedelta 40 | from pytz import utc 41 | from tzlocal import get_localzone 42 | from iso3166 import countries 43 | from math import ceil 44 | 45 | logger = logging.getLogger(__name__) 46 | 47 | 48 | class ProjectStats(object): 49 | 50 | def __init__(self, project_name, cache_instance): 51 | """ 52 | Initialize a ProjectStats class for the specified project. 53 | :param project_name: project name to calculate stats for 54 | :type project_name: str 55 | :param cache_instance: DataCache instance 56 | :type cache_instance: :py:class:`~.DiskDataCache` 57 | """ 58 | logger.debug('Initializing ProjectStats for project: %s', project_name) 59 | self.project_name = project_name 60 | self.cache = cache_instance 61 | self.cache_data = {} 62 | self.cache_dates = self._get_cache_dates() 63 | self.as_of_timestamp = self._cache_get( 64 | self.cache_dates[-1])['cache_metadata']['data_ts'] 65 | self.as_of_datetime = datetime.fromtimestamp( 66 | self.as_of_timestamp, utc).astimezone(get_localzone()) 67 | 68 | def _get_cache_dates(self): 69 | """ 70 | Get s list of dates (:py:class:`datetime.datetime`) present in cache, 71 | beginning with the longest contiguous set of dates that isn't missing 72 | more than one date in series. 73 | 74 | :return: list of datetime objects for contiguous dates in cache 75 | :rtype: ``list`` 76 | """ 77 | all_dates = self.cache.get_dates_for_project(self.project_name) 78 | dates = [] 79 | last_date = None 80 | for val in sorted(all_dates): 81 | if last_date is None: 82 | last_date = val 83 | continue 84 | if val - last_date > timedelta(hours=48): 85 | # reset dates to start from here 86 | logger.warning("Last cache date was %s, current date is %s; " 87 | "delta is too large. Starting cache date series " 88 | "at current date.", last_date, val) 89 | dates = [] 90 | last_date = val 91 | dates.append(val) 92 | # find the first download record, and only look at dates after that 93 | for idx, cache_date in enumerate(dates): 94 | data = self._cache_get(cache_date) 95 | if not self._is_empty_cache_record(data): 96 | logger.debug("First cache date with data: %s", cache_date) 97 | return dates[idx:] 98 | return dates 99 | 100 | def _is_empty_cache_record(self, rec): 101 | """ 102 | Return True if the specified cache record has no data, False otherwise. 103 | 104 | :param rec: cache record returned by :py:meth:`~._cache_get` 105 | :type rec: dict 106 | :return: True if record is empty, False otherwise 107 | :rtype: bool 108 | """ 109 | # these are taken from DataQuery.query_one_table() 110 | for k in [ 111 | 'by_version', 112 | 'by_file_type', 113 | 'by_installer', 114 | 'by_implementation', 115 | 'by_system', 116 | 'by_distro', 117 | 'by_country' 118 | ]: 119 | if k in rec and len(rec[k]) > 0: 120 | return False 121 | return True 122 | 123 | def _cache_get(self, date): 124 | """ 125 | Return cache data for the specified day; cache locally in this class. 126 | 127 | :param date: date to get data for 128 | :type date: datetime.datetime 129 | :return: cache data for date 130 | :rtype: dict 131 | """ 132 | if date in self.cache_data: 133 | logger.debug('Using class-cached data for date %s', 134 | date.strftime('%Y-%m-%d')) 135 | return self.cache_data[date] 136 | logger.debug('Getting data from cache for date %s', 137 | date.strftime('%Y-%m-%d')) 138 | data = self.cache.get(self.project_name, date) 139 | self.cache_data[date] = data 140 | return data 141 | 142 | @staticmethod 143 | def _alpha2_to_country(alpha2): 144 | """ 145 | Try to look up an alpha2 country code from the iso3166 package; return 146 | the returned name if available, otherwise the original value. Returns 147 | "unknown" (str) for None. 148 | 149 | :param alpha2: alpha2 country code 150 | :type alpha2: str 151 | :return: country name, or original value if not found 152 | :rtype: str 153 | """ 154 | if alpha2 is None: 155 | return 'unknown' 156 | try: 157 | return countries.get(alpha2).name 158 | except KeyError: 159 | return alpha2 160 | 161 | @staticmethod 162 | def _column_value(orig_val): 163 | """ 164 | Munge a BigQuery column value to what we want to store; currently 165 | just turns ``None`` into the String "unknown". 166 | 167 | :param orig_val: original field value 168 | :return: field value we cache/display 169 | :rtype: str 170 | """ 171 | if orig_val is None or orig_val == 'null': 172 | return 'unknown' 173 | return orig_val 174 | 175 | @staticmethod 176 | def _compound_column_value(k1, k2): 177 | """ 178 | Like :py:meth:`~._column_value` but collapses two unknowns into one. 179 | 180 | :param k1: first (top-level) value 181 | :param k2: second (bottom-level) value 182 | :return: display key 183 | :rtype: str 184 | """ 185 | k1 = ProjectStats._column_value(k1) 186 | k2 = ProjectStats._column_value(k2) 187 | if k1 == 'unknown' and k2 == 'unknown': 188 | return 'unknown' 189 | return '%s %s' % (k1, k2) 190 | 191 | @staticmethod 192 | def _shorten_version(ver, num_components=2): 193 | """ 194 | If ``ver`` is a dot-separated string with at least (num_components +1) 195 | components, return only the first two. Else return the original string. 196 | 197 | :param ver: version string 198 | :type ver: str 199 | :return: shortened (major, minor) version 200 | :rtype: str 201 | """ 202 | parts = ver.split('.') 203 | if len(parts) <= num_components: 204 | return ver 205 | return '.'.join(parts[:num_components]) 206 | 207 | @property 208 | def per_version_data(self): 209 | """ 210 | Return download data by version. 211 | 212 | :return: dict of cache data; keys are datetime objects, values are 213 | dict of version (str) to count (int) 214 | :rtype: dict 215 | """ 216 | ret = {} 217 | for cache_date in self.cache_dates: 218 | data = self._cache_get(cache_date) 219 | if len(data['by_version']) == 0: 220 | data['by_version'] = {'other': 0} 221 | ret[cache_date] = data['by_version'] 222 | return ret 223 | 224 | @property 225 | def per_file_type_data(self): 226 | """ 227 | Return download data by file type. 228 | 229 | :return: dict of cache data; keys are datetime objects, values are 230 | dict of file type (str) to count (int) 231 | :rtype: dict 232 | """ 233 | ret = {} 234 | for cache_date in self.cache_dates: 235 | data = self._cache_get(cache_date) 236 | if len(data['by_file_type']) == 0: 237 | data['by_file_type'] = {'other': 0} 238 | ret[cache_date] = data['by_file_type'] 239 | return ret 240 | 241 | @property 242 | def per_installer_data(self): 243 | """ 244 | Return download data by installer name and version. 245 | 246 | :return: dict of cache data; keys are datetime objects, values are 247 | dict of installer name/version (str) to count (int). 248 | :rtype: dict 249 | """ 250 | ret = {} 251 | for cache_date in self.cache_dates: 252 | data = self._cache_get(cache_date) 253 | ret[cache_date] = {} 254 | for inst_name, inst_data in data['by_installer'].items(): 255 | for inst_ver, count in inst_data.items(): 256 | k = self._compound_column_value( 257 | inst_name, 258 | self._shorten_version(inst_ver) 259 | ) 260 | ret[cache_date][k] = count 261 | if len(ret[cache_date]) == 0: 262 | ret[cache_date]['unknown'] = 0 263 | return ret 264 | 265 | @property 266 | def per_implementation_data(self): 267 | """ 268 | Return download data by python impelementation name and version. 269 | 270 | :return: dict of cache data; keys are datetime objects, values are 271 | dict of implementation name/version (str) to count (int). 272 | :rtype: dict 273 | """ 274 | ret = {} 275 | for cache_date in self.cache_dates: 276 | data = self._cache_get(cache_date) 277 | ret[cache_date] = {} 278 | for impl_name, impl_data in data['by_implementation'].items(): 279 | for impl_ver, count in impl_data.items(): 280 | k = self._compound_column_value( 281 | impl_name, 282 | self._shorten_version(impl_ver) 283 | ) 284 | ret[cache_date][k] = count 285 | if len(ret[cache_date]) == 0: 286 | ret[cache_date]['unknown'] = 0 287 | return ret 288 | 289 | @property 290 | def per_system_data(self): 291 | """ 292 | Return download data by system. 293 | 294 | :return: dict of cache data; keys are datetime objects, values are 295 | dict of system (str) to count (int) 296 | :rtype: dict 297 | """ 298 | ret = {} 299 | for cache_date in self.cache_dates: 300 | data = self._cache_get(cache_date) 301 | ret[cache_date] = { 302 | self._column_value(x): data['by_system'][x] 303 | for x in data['by_system'] 304 | } 305 | if len(ret[cache_date]) == 0: 306 | ret[cache_date]['unknown'] = 0 307 | return ret 308 | 309 | @property 310 | def per_country_data(self): 311 | """ 312 | Return download data by country. 313 | 314 | :return: dict of cache data; keys are datetime objects, values are 315 | dict of country (str) to count (int) 316 | :rtype: dict 317 | """ 318 | ret = {} 319 | for cache_date in self.cache_dates: 320 | data = self._cache_get(cache_date) 321 | ret[cache_date] = {} 322 | for cc, count in data['by_country'].items(): 323 | k = '%s (%s)' % (self._alpha2_to_country(cc), cc) 324 | ret[cache_date][k] = count 325 | if len(ret[cache_date]) == 0: 326 | ret[cache_date]['unknown'] = 0 327 | return ret 328 | 329 | @property 330 | def per_distro_data(self): 331 | """ 332 | Return download data by distro name and version. 333 | 334 | :return: dict of cache data; keys are datetime objects, values are 335 | dict of distro name/version (str) to count (int). 336 | :rtype: dict 337 | """ 338 | ret = {} 339 | for cache_date in self.cache_dates: 340 | data = self._cache_get(cache_date) 341 | ret[cache_date] = {} 342 | for distro_name, distro_data in data['by_distro'].items(): 343 | if distro_name.lower() == 'red hat enterprise linux server': 344 | distro_name = 'RHEL' 345 | for distro_ver, count in distro_data.items(): 346 | ver = self._shorten_version(distro_ver, num_components=1) 347 | if distro_name.lower() == 'os x': 348 | ver = self._shorten_version(distro_ver, 349 | num_components=2) 350 | k = self._compound_column_value(distro_name, ver) 351 | ret[cache_date][k] = count 352 | if len(ret[cache_date]) == 0: 353 | ret[cache_date]['unknown'] = 0 354 | return ret 355 | 356 | @property 357 | def downloads_per_day(self): 358 | """ 359 | Return the number of downloads per day, averaged over the past 7 days 360 | of data. 361 | 362 | :return: average number of downloads per day 363 | :rtype: int 364 | """ 365 | count, num_days = self._downloads_for_num_days(7) 366 | res = ceil(count / num_days) 367 | logger.debug("Downloads per day = (%d / %d) = %d", count, num_days, res) 368 | return res 369 | 370 | @property 371 | def downloads_per_week(self): 372 | """ 373 | Return the number of downloads in the last 7 days. 374 | 375 | :return: number of downloads in the last 7 days; if we have less than 376 | 7 days of data, returns None. 377 | :rtype: int 378 | """ 379 | if len(self.cache_dates) < 7: 380 | logger.error("Only have %d days of data; cannot calculate " 381 | "downloads per week", len(self.cache_dates)) 382 | return None 383 | count, _ = self._downloads_for_num_days(7) 384 | logger.debug("Downloads per week = %d", count) 385 | return count 386 | 387 | @property 388 | def downloads_per_month(self): 389 | """ 390 | Return the number of downloads in the last 30 days. 391 | 392 | Uses :py:meth:`~._downloads_for_num_days` to retrieve the data. 393 | 394 | :return: number of downloads in the last 30 days; if we have less than 395 | 30 days of data, returns None. 396 | :rtype: int 397 | """ 398 | if len(self.cache_dates) < 30: 399 | logger.error("Only have %d days of data; cannot calculate " 400 | "downloads per month", len(self.cache_dates)) 401 | return None 402 | count, _ = self._downloads_for_num_days(30) 403 | logger.debug("Downloads per month = %d", count) 404 | return count 405 | 406 | def _downloads_for_num_days(self, num_days): 407 | """ 408 | Given a number of days of historical data to look at (starting with 409 | today and working backwards), return the total number of downloads 410 | for that time range, and the number of days of data we had (in cases 411 | where we had less data than requested). 412 | 413 | :param num_days: number of days of data to look at 414 | :type num_days: int 415 | :return: 2-tuple of (download total, number of days of data) 416 | :rtype: tuple 417 | """ 418 | logger.debug("Getting download total for last %d days", num_days) 419 | dates = self.cache_dates 420 | logger.debug("Cache has %d days of data", len(dates)) 421 | if len(dates) > num_days: 422 | dates = dates[(-1 * num_days):] 423 | logger.debug("Looking at last %d days of data", len(dates)) 424 | dl_sum = 0 425 | for cache_date in dates: 426 | data = self._cache_get(cache_date) 427 | dl_sum += sum(data['by_version'].values()) 428 | logger.debug("Sum of download counts: %d", dl_sum) 429 | return dl_sum, len(dates) 430 | -------------------------------------------------------------------------------- /pypi_download_stats/runner.py: -------------------------------------------------------------------------------- 1 | """ 2 | The latest version of this package is available at: 3 | 4 | 5 | ################################################################################## 6 | Copyright 2016 Jason Antman 7 | 8 | This file is part of pypi-download-stats, also known as pypi-download-stats. 9 | 10 | pypi-download-stats is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU Affero General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | pypi-download-stats is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU Affero General Public License for more details. 19 | 20 | You should have received a copy of the GNU Affero General Public License 21 | along with pypi-download-stats. If not, see . 22 | 23 | The Copyright and Authors attributions contained herein may not be removed or 24 | otherwise altered, except to add the Author attribution of a contributor to 25 | this work. (Additional Terms pursuant to Section 7b of the AGPL v3) 26 | ################################################################################## 27 | While not legally required, I sincerely request that anyone who finds 28 | bugs please submit them at or 29 | to me via email, and that you send any contributions or improvements 30 | either as a pull request on GitHub, or to me via email. 31 | ################################################################################## 32 | 33 | AUTHORS: 34 | Jason Antman 35 | ################################################################################## 36 | """ 37 | 38 | import sys 39 | import argparse 40 | import logging 41 | import os 42 | 43 | try: 44 | import xmlrpclib 45 | except ImportError: 46 | import xmlrpc.client as xmlrpclib 47 | 48 | from pypi_download_stats.dataquery import DataQuery 49 | from pypi_download_stats.diskdatacache import DiskDataCache 50 | from pypi_download_stats.outputgenerator import OutputGenerator 51 | from pypi_download_stats.projectstats import ProjectStats 52 | from pypi_download_stats.version import PROJECT_URL, VERSION 53 | 54 | FORMAT = "[%(asctime)s %(levelname)s] %(message)s" 55 | logging.basicConfig(level=logging.WARNING, format=FORMAT) 56 | logger = logging.getLogger() 57 | 58 | # suppress googleapiclient internal logging below WARNING level 59 | googleapiclient_log = logging.getLogger("googleapiclient") 60 | googleapiclient_log.setLevel(logging.WARNING) 61 | googleapiclient_log.propagate = True 62 | 63 | # suppress oauth2client internal logging below WARNING level 64 | oauth2client_log = logging.getLogger("oauth2client") 65 | oauth2client_log.setLevel(logging.WARNING) 66 | oauth2client_log.propagate = True 67 | 68 | 69 | def parse_args(argv): 70 | """ 71 | Use Argparse to parse command-line arguments. 72 | 73 | :param argv: list of arguments to parse (``sys.argv[1:]``) 74 | :type argv: ``list`` 75 | :return: parsed arguments 76 | :rtype: :py:class:`argparse.Namespace` 77 | """ 78 | p = argparse.ArgumentParser( 79 | description='pypi-download-stats - Calculate detailed download stats ' 80 | 'and generate HTML and badges for PyPI packages - ' 81 | '<%s>' % PROJECT_URL, 82 | prog='pypi-download-stats' 83 | ) 84 | p.add_argument('-V', '--version', action='version', 85 | version='%(prog)s ' + VERSION) 86 | p.add_argument('-v', '--verbose', dest='verbose', action='count', 87 | default=0, 88 | help='verbose output. specify twice for debug-level output.') 89 | m = p.add_mutually_exclusive_group() 90 | m.add_argument('-Q', '--no-query', dest='query', action='store_false', 91 | default=True, help='do not query; just generate output ' 92 | 'from cached data') 93 | m.add_argument('-G', '--no-generate', dest='generate', action='store_false', 94 | default=True, help='do not generate output; just query ' 95 | 'data and cache results') 96 | p.add_argument('-o', '--out-dir', dest='out_dir', action='store', type=str, 97 | default='./pypi-stats', help='output directory (default: ' 98 | './pypi-stats') 99 | p.add_argument('-p', '--project-id', dest='project_id', action='store', 100 | type=str, default=None, 101 | help='ProjectID for your Google Cloud user, if not using ' 102 | 'service account credentials JSON file') 103 | # @TODO this is tied to the DiskDataCache class 104 | p.add_argument('-c', '--cache-dir', dest='cache_dir', action='store', 105 | type=str, default='./pypi-stats-cache', 106 | help='stats cache directory (default: ./pypi-stats-cache)') 107 | p.add_argument('-B', '--backfill-num-days', dest='backfill_days', type=int, 108 | action='store', default=7, 109 | help='number of days of historical data to backfill, if ' 110 | 'missing (defaut: 7). Note this may incur BigQuery ' 111 | 'charges. Set to -1 to backfill all available history.') 112 | g = p.add_mutually_exclusive_group() 113 | g.add_argument('-P', '--project', dest='PROJECT', action='append', type=str, 114 | help='project name to query/generate stats for (can be ' 115 | 'specified more than once; ' 116 | 'this will reduce query cost for multiple projects)') 117 | g.add_argument('-U', '--user', dest='user', action='store', type=str, 118 | help='Run for all PyPI projects owned by the specified' 119 | 'user.') 120 | args = p.parse_args(argv) 121 | return args 122 | 123 | 124 | def set_log_info(): 125 | """set logger level to INFO""" 126 | set_log_level_format(logging.INFO, 127 | '%(asctime)s %(levelname)s:%(name)s:%(message)s') 128 | 129 | 130 | def set_log_debug(): 131 | """set logger level to DEBUG, and debug-level output format""" 132 | set_log_level_format( 133 | logging.DEBUG, 134 | "%(asctime)s [%(levelname)s %(filename)s:%(lineno)s - " 135 | "%(name)s.%(funcName)s() ] %(message)s" 136 | ) 137 | 138 | 139 | def set_log_level_format(level, format): 140 | """ 141 | Set logger level and format. 142 | 143 | :param level: logging level; see the :py:mod:`logging` constants. 144 | :type level: int 145 | :param format: logging formatter format string 146 | :type format: str 147 | """ 148 | formatter = logging.Formatter(fmt=format) 149 | logger.handlers[0].setFormatter(formatter) 150 | logger.setLevel(level) 151 | 152 | 153 | def _pypi_get_projects_for_user(username): 154 | """ 155 | Given the username of a PyPI user, return a list of all of the user's 156 | projects from the XMLRPC interface. 157 | 158 | See: https://wiki.python.org/moin/PyPIXmlRpc 159 | 160 | :param username: PyPI username 161 | :type username: str 162 | :return: list of string project names 163 | :rtype: ``list`` 164 | """ 165 | client = xmlrpclib.ServerProxy('https://pypi.python.org/pypi') 166 | pkgs = client.user_packages(username) # returns [role, package] 167 | return [x[1] for x in pkgs] 168 | 169 | 170 | def main(args=None): 171 | """ 172 | Main entry point 173 | """ 174 | # parse args 175 | if args is None: 176 | args = parse_args(sys.argv[1:]) 177 | 178 | # set logging level 179 | if args.verbose > 1: 180 | set_log_debug() 181 | elif args.verbose == 1: 182 | set_log_info() 183 | 184 | outpath = os.path.abspath(os.path.expanduser(args.out_dir)) 185 | cachepath = os.path.abspath(os.path.expanduser(args.cache_dir)) 186 | cache = DiskDataCache(cache_path=cachepath) 187 | 188 | if args.user: 189 | args.PROJECT = _pypi_get_projects_for_user(args.user) 190 | 191 | if args.query: 192 | DataQuery(args.project_id, args.PROJECT, cache).run_queries( 193 | backfill_num_days=args.backfill_days) 194 | else: 195 | logger.warning('Query disabled by command-line flag; operating on ' 196 | 'cached data only.') 197 | if not args.generate: 198 | logger.warning('Output generation disabled by command-line flag; ' 199 | 'exiting now.') 200 | raise SystemExit(0) 201 | for proj in args.PROJECT: 202 | logger.info('Generating output for: %s', proj) 203 | stats = ProjectStats(proj, cache) 204 | outdir = os.path.join(outpath, proj) 205 | OutputGenerator(proj, stats, outdir).generate() 206 | 207 | 208 | if __name__ == "__main__": 209 | args = parse_args(sys.argv[1:]) 210 | main(args) 211 | -------------------------------------------------------------------------------- /pypi_download_stats/templates/badges.html: -------------------------------------------------------------------------------- 1 | 2 | {%- for badgename in badges %}{{ badges[badgename] }} {%- endfor %} 3 | -------------------------------------------------------------------------------- /pypi_download_stats/templates/base.html: -------------------------------------------------------------------------------- 1 | {% from "graph_macro.html" import graph_macro %} 2 | 3 | 4 | 5 | Download Report for PyPI project {{ project }} 6 | 7 | 8 | 9 | 10 | 11 | 12 | 68 | 69 | 79 | 80 | 202 | {{ resources }} 203 | {%- for graphkey in graph_keys %} 204 | 205 | {{ graphs[graphkey]['script'] }} 206 | 207 | {%- endfor %} 208 | 209 | 210 |

Download Report for PyPI project {{ project }}

211 |

As of {{ cache_date|format_date_long }}

212 |
213 | {% include 'badges.html' %} 214 |
215 | 218 |
219 | {%- for graphkey in graph_keys %}{{ graph_macro(graphkey, graphs[graphkey]) }}{%- endfor %} 220 |
221 | 226 | 227 | 228 | -------------------------------------------------------------------------------- /pypi_download_stats/templates/graph_macro.html: -------------------------------------------------------------------------------- 1 | {%- macro graph_macro(graph_key, gdata) %} 2 | 3 |

{{ gdata['title'] }} (hide)

4 |
5 |
6 | {{ gdata['div'] }} 7 |
8 |

Show Data Table

9 |
10 | {{ graph_table_macro(gdata['raw_data']) }} 11 |
12 |
13 | 14 | {%- endmacro %} 15 | {%- macro graph_table_macro(data) %} 16 | {%- set cols = data|data_columns %} 17 | 18 | 19 | 20 | 21 | {% for col in cols %}{% endfor %} 22 | 23 | 24 | 25 | {%- for dt in data|sort %} 26 | 27 | 28 | {%- for col in cols %} 29 | 30 | {%- endfor %} 31 | 32 | {%- endfor %} 33 | 34 |
Date{{ col }}
{{ dt|format_date_ymd }}{{ data[dt][col] }}
35 | {%- endmacro %} -------------------------------------------------------------------------------- /pypi_download_stats/templates/nav.html: -------------------------------------------------------------------------------- 1 | 2 |

Contents (hide all)

3 | 8 | -------------------------------------------------------------------------------- /pypi_download_stats/tests/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | The latest version of this package is available at: 3 | 4 | 5 | ################################################################################## 6 | Copyright 2016 Jason Antman 7 | 8 | This file is part of pypi-download-stats, also known as pypi-download-stats. 9 | 10 | pypi-download-stats is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU Affero General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | pypi-download-stats is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU Affero General Public License for more details. 19 | 20 | You should have received a copy of the GNU Affero General Public License 21 | along with pypi-download-stats. If not, see . 22 | 23 | The Copyright and Authors attributions contained herein may not be removed or 24 | otherwise altered, except to add the Author attribution of a contributor to 25 | this work. (Additional Terms pursuant to Section 7b of the AGPL v3) 26 | ################################################################################## 27 | While not legally required, I sincerely request that anyone who finds 28 | bugs please submit them at or 29 | to me via email, and that you send any contributions or improvements 30 | either as a pull request on GitHub, or to me via email. 31 | ################################################################################## 32 | 33 | AUTHORS: 34 | Jason Antman 35 | ################################################################################## 36 | """ 37 | -------------------------------------------------------------------------------- /pypi_download_stats/tests/test_runner.py: -------------------------------------------------------------------------------- 1 | """ 2 | The latest version of this package is available at: 3 | 4 | 5 | ################################################################################## 6 | Copyright 2016 Jason Antman 7 | 8 | This file is part of pypi-download-stats, also known as pypi-download-stats. 9 | 10 | pypi-download-stats is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU Affero General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | pypi-download-stats is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU Affero General Public License for more details. 19 | 20 | You should have received a copy of the GNU Affero General Public License 21 | along with pypi-download-stats. If not, see . 22 | 23 | The Copyright and Authors attributions contained herein may not be removed or 24 | otherwise altered, except to add the Author attribution of a contributor to 25 | this work. (Additional Terms pursuant to Section 7b of the AGPL v3) 26 | ################################################################################## 27 | While not legally required, I sincerely request that anyone who finds 28 | bugs please submit them at or 29 | to me via email, and that you send any contributions or improvements 30 | either as a pull request on GitHub, or to me via email. 31 | ################################################################################## 32 | 33 | AUTHORS: 34 | Jason Antman 35 | ################################################################################## 36 | """ 37 | 38 | import sys 39 | import logging 40 | 41 | from pypi_download_stats.runner import ( 42 | set_log_level_format, set_log_debug, set_log_info 43 | ) 44 | 45 | # https://code.google.com/p/mock/issues/detail?id=249 46 | # py>=3.4 should use unittest.mock not the mock package on pypi 47 | if ( 48 | sys.version_info[0] < 3 or 49 | sys.version_info[0] == 3 and sys.version_info[1] < 4 50 | ): 51 | from mock import patch, call, Mock, DEFAULT # noqa 52 | else: 53 | from unittest.mock import patch, call, Mock, DEFAULT # noqa 54 | 55 | pbm = 'pypi_download_stats.runner' 56 | 57 | 58 | class TestRunner(object): 59 | 60 | def test_set_log_info(self): 61 | with patch('%s.set_log_level_format' % pbm) as mock_set: 62 | set_log_info() 63 | assert mock_set.mock_calls == [ 64 | call(logging.INFO, '%(asctime)s %(levelname)s:%(name)s:%(message)s') 65 | ] 66 | 67 | def test_set_log_debug(self): 68 | with patch('%s.set_log_level_format' % pbm) as mock_set: 69 | set_log_debug() 70 | assert mock_set.mock_calls == [ 71 | call(logging.DEBUG, 72 | "%(asctime)s [%(levelname)s %(filename)s:%(lineno)s - " 73 | "%(name)s.%(funcName)s() ] %(message)s") 74 | ] 75 | 76 | def test_set_log_level_format(self): 77 | mock_handler = Mock(spec_set=logging.Handler) 78 | with patch('%s.logger' % pbm) as mock_logger: 79 | with patch('%s.logging.Formatter' % pbm) as mock_formatter: 80 | type(mock_logger).handlers = [mock_handler] 81 | set_log_level_format(5, 'foo') 82 | assert mock_formatter.mock_calls == [ 83 | call(fmt='foo') 84 | ] 85 | assert mock_handler.mock_calls == [ 86 | call.setFormatter(mock_formatter.return_value) 87 | ] 88 | assert mock_logger.mock_calls == [ 89 | call.setLevel(5) 90 | ] 91 | -------------------------------------------------------------------------------- /pypi_download_stats/tests/test_version.py: -------------------------------------------------------------------------------- 1 | """ 2 | The latest version of this package is available at: 3 | 4 | 5 | ################################################################################## 6 | Copyright 2016 Jason Antman 7 | 8 | This file is part of pypi-download-stats, also known as pypi-download-stats. 9 | 10 | pypi-download-stats is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU Affero General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | pypi-download-stats is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU Affero General Public License for more details. 19 | 20 | You should have received a copy of the GNU Affero General Public License 21 | along with pypi-download-stats. If not, see . 22 | 23 | The Copyright and Authors attributions contained herein may not be removed or 24 | otherwise altered, except to add the Author attribution of a contributor to 25 | this work. (Additional Terms pursuant to Section 7b of the AGPL v3) 26 | ################################################################################## 27 | While not legally required, I sincerely request that anyone who finds 28 | bugs please submit them at or 29 | to me via email, and that you send any contributions or improvements 30 | either as a pull request on GitHub, or to me via email. 31 | ################################################################################## 32 | 33 | AUTHORS: 34 | Jason Antman 35 | ################################################################################## 36 | """ 37 | 38 | import pypi_download_stats.version as version 39 | 40 | import re 41 | 42 | 43 | class TestVersion(object): 44 | 45 | def test_project_url(self): 46 | expected = 'https://github.com/jantman/pypi-download-stats' 47 | assert version.PROJECT_URL == expected 48 | 49 | def test_is_semver(self): 50 | # see: 51 | # https://github.com/mojombo/semver.org/issues/59#issuecomment-57884619 52 | semver_ptn = re.compile( 53 | r'^' 54 | r'(?P(?:' 55 | r'0|(?:[1-9]\d*)' 56 | r'))' 57 | r'\.' 58 | r'(?P(?:' 59 | r'0|(?:[1-9]\d*)' 60 | r'))' 61 | r'\.' 62 | r'(?P(?:' 63 | r'0|(?:[1-9]\d*)' 64 | r'))' 65 | r'(?:-(?P' 66 | r'[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*' 67 | r'))?' 68 | r'(?:\+(?P' 69 | r'[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*' 70 | r'))?' 71 | r'$' 72 | ) 73 | assert semver_ptn.match(version.VERSION) is not None 74 | -------------------------------------------------------------------------------- /pypi_download_stats/version.py: -------------------------------------------------------------------------------- 1 | """ 2 | The latest version of this package is available at: 3 | 4 | 5 | ################################################################################## 6 | Copyright 2016 Jason Antman 7 | 8 | This file is part of pypi-download-stats, also known as pypi-download-stats. 9 | 10 | pypi-download-stats is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU Affero General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | pypi-download-stats is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU Affero General Public License for more details. 19 | 20 | You should have received a copy of the GNU Affero General Public License 21 | along with pypi-download-stats. If not, see . 22 | 23 | The Copyright and Authors attributions contained herein may not be removed or 24 | otherwise altered, except to add the Author attribution of a contributor to 25 | this work. (Additional Terms pursuant to Section 7b of the AGPL v3) 26 | ################################################################################## 27 | While not legally required, I sincerely request that anyone who finds 28 | bugs please submit them at or 29 | to me via email, and that you send any contributions or improvements 30 | either as a pull request on GitHub, or to me via email. 31 | ################################################################################## 32 | 33 | AUTHORS: 34 | Jason Antman 35 | ################################################################################## 36 | """ 37 | 38 | VERSION = '0.2.2' 39 | PROJECT_URL = 'https://github.com/jantman/pypi-download-stats' 40 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | pep8ignore = 3 | lib/* ALL 4 | lib64/* ALL 5 | pep8maxlinelength = 80 6 | 7 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal=1 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """ 2 | The latest version of this package is available at: 3 | 4 | 5 | ################################################################################## 6 | Copyright 2016 Jason Antman 7 | 8 | This file is part of pypi-download-stats, also known as pypi-download-stats. 9 | 10 | pypi-download-stats is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU Affero General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | pypi-download-stats is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU Affero General Public License for more details. 19 | 20 | You should have received a copy of the GNU Affero General Public License 21 | along with pypi-download-stats. If not, see . 22 | 23 | The Copyright and Authors attributions contained herein may not be removed or 24 | otherwise altered, except to add the Author attribution of a contributor to 25 | this work. (Additional Terms pursuant to Section 7b of the AGPL v3) 26 | ################################################################################## 27 | While not legally required, I sincerely request that anyone who finds 28 | bugs please submit them at or 29 | to me via email, and that you send any contributions or improvements 30 | either as a pull request on GitHub, or to me via email. 31 | ################################################################################## 32 | 33 | AUTHORS: 34 | Jason Antman 35 | ################################################################################## 36 | """ 37 | 38 | from setuptools import setup, find_packages 39 | from pypi_download_stats.version import VERSION, PROJECT_URL 40 | 41 | with open('README.rst') as file: 42 | long_description = file.read() 43 | 44 | requires = [ 45 | 'google-api-python-client>=1.5.0', 46 | 'oauth2client>=3.0.0', 47 | 'bokeh==0.12.1', 48 | 'pandas>=0.18,<1.0', 49 | 'tzlocal', 50 | 'pytz', 51 | 'iso3166', 52 | 'requests>2.0,<3.0' 53 | ] 54 | 55 | classifiers = [ 56 | 'Development Status :: 7 - Inactive', 57 | 'Environment :: Console', 58 | 'Intended Audience :: Developers', 59 | 'License :: OSI Approved :: GNU Affero General Public License v3 ' 60 | 'or later (AGPLv3+)', 61 | 'Natural Language :: English', 62 | 'Operating System :: OS Independent', 63 | 'Programming Language :: Python', 64 | 'Programming Language :: Python :: 2.7', 65 | 'Programming Language :: Python :: 3.5', 66 | 'Programming Language :: Python :: 3.6', 67 | 'Topic :: Internet :: Log Analysis', 68 | 'Topic :: Software Development', 69 | 'Topic :: Utilities' 70 | ] 71 | 72 | setup( 73 | name='pypi-download-stats', 74 | version=VERSION, 75 | author='Jason Antman', 76 | author_email='jason@jasonantman.com', 77 | packages=find_packages(), 78 | package_data={'pypi_download_stats': ['templates/*.html']}, 79 | url=PROJECT_URL, 80 | description='Calculate detailed download stats and generate HTML and ' 81 | 'badges for PyPI packages', 82 | long_description=long_description, 83 | install_requires=requires, 84 | keywords="pypi warehouse download stats badge", 85 | classifiers=classifiers, 86 | entry_points=""" 87 | [console_scripts] 88 | pypi-download-stats = pypi_download_stats.runner:main 89 | """, 90 | ) 91 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27,py35,py36,docs 3 | 4 | [testenv] 5 | deps = 6 | cov-core 7 | coverage 8 | execnet 9 | pep8 10 | py 11 | pytest>=2.8.3 12 | pytest-cache 13 | pytest-cov 14 | pytest-pep8 15 | pytest-flakes 16 | mock 17 | freezegun 18 | pytest-blockage 19 | 20 | passenv=TRAVIS* 21 | setenv = 22 | TOXINIDIR={toxinidir} 23 | TOXDISTDIR={distdir} 24 | sitepackages = False 25 | whitelist_externals = env test 26 | 27 | commands = 28 | python --version 29 | virtualenv --version 30 | pip --version 31 | pip freeze 32 | py.test -rxs -vv --durations=10 --pep8 --flakes --blockage --cov-report term-missing --cov-report xml --cov-report html --cov-config {toxinidir}/.coveragerc --cov=pypi_download_stats {posargs} pypi_download_stats 33 | 34 | # always recreate the venv 35 | recreate = True 36 | 37 | [testenv:docs] 38 | # this really just makes sure README.rst will parse on pypi 39 | passenv = TRAVIS* CONTINUOUS_INTEGRATION AWS* READTHEDOCS* 40 | setenv = 41 | TOXINIDIR={toxinidir} 42 | TOXDISTDIR={distdir} 43 | CI=true 44 | deps = 45 | docutils 46 | pygments 47 | sphinx 48 | sphinx_rtd_theme 49 | basepython = python2.7 50 | commands = 51 | python --version 52 | virtualenv --version 53 | pip --version 54 | pip freeze 55 | rst2html.py --halt=2 README.rst /dev/null 56 | sphinx-apidoc pypi_download_stats pypi_download_stats/tests -o {toxinidir}/docs/source -e -f -M 57 | # link check 58 | # -n runs in nit-picky mode 59 | # -W turns warnings into errors 60 | sphinx-build -a -n -W -b linkcheck {toxinidir}/docs/source {toxinidir}/docs/build/html 61 | # build 62 | sphinx-build -a -n -W -b html {toxinidir}/docs/source {toxinidir}/docs/build/html 63 | {toxinidir}/docs/are_docs_changed.sh 64 | --------------------------------------------------------------------------------