├── .gitattributes ├── .github ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.rst ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── pythonpublish.yml ├── .gitignore ├── .mailmap ├── Custom_Firebase_Database_Backend.md ├── LICENSE ├── README.md ├── firebase_orm ├── __init__.py ├── exceptions.py └── models │ ├── __init__.py │ ├── base.py │ ├── fields │ └── __init__.py │ └── manager.py ├── settings.py ├── setup.cfg ├── setup.py └── tests ├── conftest.py ├── field_tests └── id_test.py ├── firebase_fixture.py ├── model_tests ├── all_test.py ├── fixture.py ├── get_test.py ├── model_test.py └── save_test.py ├── orm_fixture.py └── pytest.ini /.gitattributes: -------------------------------------------------------------------------------- 1 | 2 | docs/* linguist-documentation 3 | 4 | *.css linguist-detectable=false 5 | 6 | *.html linguist-detectable=false 7 | 8 | -------------------------------------------------------------------------------- /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | 2 | # Contributor Covenant Code of Conduct 3 | 4 | ## Our Pledge 5 | 6 | In the interest of fostering an open and welcoming environment, we as 7 | contributors and maintainers pledge to making participation in our project and 8 | our community a harassment-free experience for everyone, regardless of age, body 9 | size, disability, ethnicity, sex characteristics, gender identity and expression, 10 | level of experience, education, socio-economic status, nationality, personal 11 | appearance, race, religion, or sexual identity and orientation. 12 | 13 | ## Our Standards 14 | 15 | Examples of behavior that contributes to creating a positive environment 16 | include: 17 | 18 | * Using welcoming and inclusive language 19 | * Being respectful of differing viewpoints and experiences 20 | * Gracefully accepting constructive criticism 21 | * Focusing on what is best for the community 22 | * Showing empathy towards other community members 23 | 24 | Examples of unacceptable behavior by participants include: 25 | 26 | * The use of sexualized language or imagery and unwelcome sexual attention or 27 | advances 28 | * Trolling, insulting/derogatory comments, and personal or political attacks 29 | * Public or private harassment 30 | * Publishing others' private information, such as a physical or electronic 31 | address, without explicit permission 32 | * Other conduct which could reasonably be considered inappropriate in a 33 | professional setting 34 | 35 | ## Our Responsibilities 36 | 37 | Project maintainers are responsible for clarifying the standards of acceptable 38 | behavior and are expected to take appropriate and fair corrective action in 39 | response to any instances of unacceptable behavior. 40 | 41 | Project maintainers have the right and responsibility to remove, edit, or 42 | reject comments, commits, code, wiki edits, issues, and other contributions 43 | that are not aligned to this Code of Conduct, or to ban temporarily or 44 | permanently any contributor for other behaviors that they deem inappropriate, 45 | threatening, offensive, or harmful. 46 | 47 | ## Scope 48 | 49 | This Code of Conduct applies both within project spaces and in public spaces 50 | when an individual is representing the project or its community. Examples of 51 | representing a project or community include using an official project e-mail 52 | address, posting via an official social media account, or acting as an appointed 53 | representative at an online or offline event. Representation of a project may be 54 | further defined and clarified by project maintainers. 55 | 56 | ## Enforcement 57 | 58 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 59 | reported by contacting the project team at musyoki.tralah@students.jkuat.ac.ke. All 60 | complaints will be reviewed and investigated and will result in a response that 61 | is deemed necessary and appropriate to the circumstances. The project team is 62 | obligated to maintain confidentiality with regard to the reporter of an incident. 63 | Further details of specific enforcement policies may be posted separately. 64 | 65 | Project maintainers who do not follow or enforce the Code of Conduct in good 66 | faith may face temporary or permanent repercussions as determined by other 67 | members of the project's leadership. 68 | 69 | ## Attribution 70 | 71 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 72 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 73 | 74 | [homepage]: https://www.contributor-covenant.org 75 | 76 | For answers to common questions about this code of conduct, see 77 | https://www.contributor-covenant.org/faq 78 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | 2 | ======================= 3 | Contributing Guidelines 4 | ======================= 5 | 6 | Thanks for your interest in contributing to this project! Contributions are 7 | welcome and very much appreciated. If this is your first time contributing to a 8 | Free and Open Source Software project, consider reading `How to Contribute to 9 | Open Source`_ in the Open Source Guides. Additionally, to maximize the chance 10 | that your contribution will be accepted and minimize wasted effort, consider the 11 | following guidelines: 12 | 13 | 14 | Tests Must Pass 15 | =============== 16 | 17 | In order for a pull request to be accepted, it must build and test successfully 18 | on the continuous integration systems. GitHub displays a build status 19 | indicator on the pull request. If the build is broken, please fix it (or add a 20 | comment if you think the pull request is not the cause of the breakage). 21 | 22 | The CI build runs several linters and tests. These can be run locally by 23 | invoking ``tox``. Disabling linter rules using inline configuration is 24 | acceptable, where justified. Disable specific rules where possible (i.e. 25 | ``# noqa: F401`` rather than just ``# noqa``). 26 | 27 | 28 | Add Tests Where Reasonable 29 | ========================== 30 | 31 | If the pull request fixes a bug or adds a feature, consider adding a test to 32 | ensure the bug does not reoccur and the feature works as expected. If testing 33 | is not straightforward, feel free to submit the pull request without tests. 34 | How to test and whether testing is required can be discussed during the review 35 | process. 36 | 37 | 38 | Consider Discussing Big Changes First 39 | ===================================== 40 | 41 | If the desired change is large, complex, backwards-incompatible, can have 42 | significantly differing implementations, or may not be in scope for this 43 | project, opening an issue to discuss the change before writing the code can 44 | avoid frustration and save a lot of time and effort. 45 | 46 | This is not a hard requirement. If you'd rather start discussing a big change 47 | with a proposed implementation, feel free. Be aware that the code may be 48 | rejected outright, or require many changes before it is acceptable. 49 | 50 | .. _How to Contribute to Open Source: https://opensource.guide/how-to-contribute/ 51 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | 2 | github: TralahM 3 | patreon: TralahM 4 | custom: "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WFKVHBRCYEE6S&source=url" 5 | # Custom: [TralahM.github.io,TralahTek.github.io,] 6 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | 2 | --- 3 | name: Bug report 4 | about: Create a report to help us improve 5 | title: '' 6 | labels: '' 7 | assignees: '' 8 | 9 | --- 10 | 11 | **Describe the bug** 12 | A clear and concise description of what the bug is. 13 | 14 | **To Reproduce** 15 | Steps to reproduce the behavior: 16 | 1. Go to '...' 17 | 2. Click on '....' 18 | 3. Scroll down to '....' 19 | 4. See error 20 | 21 | **Expected behavior** 22 | A clear and concise description of what you expected to happen. 23 | 24 | **Screenshots** 25 | If applicable, add screenshots to help explain your problem. 26 | 27 | **Desktop (please complete the following information):** 28 | - OS: [e.g. iOS] 29 | - Browser [e.g. chrome, safari] 30 | - Version [e.g. 22] 31 | 32 | **Smartphone (please complete the following information):** 33 | - Device: [e.g. iPhone6] 34 | - OS: [e.g. iOS8.1] 35 | - Browser [e.g. stock browser, safari] 36 | - Version [e.g. 22] 37 | 38 | **Additional context** 39 | Add any other context about the problem here. 40 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | 2 | --- 3 | name: Feature request 4 | about: Suggest an idea for this project 5 | title: '' 6 | labels: '' 7 | assignees: '' 8 | 9 | --- 10 | 11 | **Is your feature request related to a problem? Please describe.** 12 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 13 | 14 | **Describe the solution you'd like** 15 | A clear and concise description of what you want to happen. 16 | 17 | **Describe alternatives you've considered** 18 | A clear and concise description of any alternative solutions or features you've considered. 19 | 20 | **Additional context** 21 | Add any other context or screenshots about the feature request here. 22 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | __IMPORTANT:__ Please take note of the below checklist, especially the first two items. 3 | 4 | # Pull Request Checklist 5 | 6 | - [ ] All pull requests must include the Contributor License Agreement (see below). 7 | 8 | - [ ] Code should conform to the following: 9 | 10 | - [ ] pep8 compliant with some exceptions (see pytest.ini) 11 | 12 | - [ ] 100% test coverage with pytest (with valid tests). If you have difficulty 13 | writing tests for the code, feel free to ask for help or submit the PR without tests. 14 | 15 | - [ ] Complete, correctly-formatted documentation for all classes, functions and methods. 16 | 17 | - [ ] documentation has been rebuilt with ``tox -e docs`` 18 | 19 | - [ ] All modules should have (and use) module-level loggers. 20 | 21 | - [ ] **Commit messages** should be meaningful, and reference the Issue number 22 | if you're working on a GitHub issue (i.e. "issue #x - "). Please 23 | refrain from using the "fixes #x" notation unless you are *sure* that the 24 | the issue is fixed in that commit. 25 | 26 | - [ ] Git history is fully intact; please do not squash or rewrite history. 27 | 28 | ## Contributor License Agreement 29 | 30 | By submitting this work for inclusion in python-package-skeleton, I agree to the following terms: 31 | 32 | * The contribution included in this request (and any subsequent revisions or versions of it) 33 | is being made under the same license as the python-package-skeleton project (the Affero GPL v3, 34 | or any subsequent version of that license if adopted by python-package-skeleton). 35 | * My contribution may perpetually be included in and distributed with python-package-skeleton; submitting 36 | this pull request grants a perpetual, global, unlimited license for it to be used and distributed 37 | under the terms of python-package-skeleton's license. 38 | * I have the legal power and rights to agree to these terms. 39 | -------------------------------------------------------------------------------- /.github/workflows/pythonpublish.yml: -------------------------------------------------------------------------------- 1 | 2 | # This workflows will upload a Python Package using Twine when a release is created 3 | # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries 4 | 5 | name: Upload Python Package 6 | 7 | on: 8 | release: 9 | types: [created] 10 | 11 | jobs: 12 | deploy: 13 | 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - uses: actions/checkout@v2 18 | - name: Set up Python 19 | uses: actions/setup-python@v1 20 | with: 21 | python-version: '3.x' 22 | - name: Install dependencies 23 | run: | 24 | python -m pip install --upgrade pip 25 | pip install setuptools wheel twine 26 | - name: Build and publish 27 | env: 28 | TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} 29 | TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} 30 | run: | 31 | python setup.py sdist bdist_wheel 32 | twine upload dist/* 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Dolphin 3 | .directory 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # C extensions 10 | *.so 11 | 12 | # Distribution / packaging 13 | .Python 14 | env/ 15 | build/ 16 | develop-eggs/ 17 | dist/ 18 | downloads/ 19 | eggs/ 20 | .eggs/ 21 | lib/ 22 | lib64/ 23 | parts/ 24 | sdist/ 25 | var/ 26 | wheels/ 27 | *.egg-info/ 28 | .installed.cfg 29 | *.egg 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .coverage 45 | .coverage.* 46 | nohup.out 47 | .cache 48 | nosetests.xml 49 | coverage.xml 50 | *.cover 51 | .hypothesis/ 52 | 53 | # Translations 54 | *.mo 55 | *.pot 56 | 57 | # Django stuff: 58 | *.log 59 | local_settings.py 60 | 61 | # Flask stuff: 62 | instance/ 63 | .webassets-cache 64 | 65 | # Scrapy stuff: 66 | .scrapy 67 | 68 | # Sphinx documentation 69 | docs/_build/ 70 | 71 | # PyBuilder 72 | target/ 73 | 74 | # Jupyter Notebook 75 | .ipynb_checkpoints 76 | 77 | # pyenv 78 | .python-version 79 | 80 | # celery beat schedule file 81 | celerybeat-schedule* 82 | 83 | # SageMath parsed files 84 | *.sage.py 85 | 86 | # dotenv 87 | .env 88 | 89 | # virtualenv 90 | .venv 91 | venv/ 92 | ENV/ 93 | env/ 94 | 95 | # Spyder project settings 96 | .spyderproject 97 | .spyproject 98 | 99 | # Rope project settings 100 | .ropeproject/ 101 | 102 | # mkdocs documentation 103 | /site 104 | 105 | # mypy 106 | .mypy_cache/ 107 | 108 | # PyCharm 109 | .idea/ 110 | 111 | .*~ 112 | 113 | # Jekyll Documentation 114 | _site 115 | .sass-cache 116 | .jekyll-metadata 117 | .jekyll-cache/* 118 | .jekyll-cache/* 119 | 120 | # nohup.out files 121 | *.out 122 | stime 123 | -------------------------------------------------------------------------------- /.mailmap: -------------------------------------------------------------------------------- 1 | 2 | # Prevent git from showing duplicate names with commands like "git shortlog" 3 | # See the manpage of git-shortlog for details. 4 | # The syntax is: 5 | # Name that should be used Bad name 6 | # 7 | # You can skip Bad name if it is the same as the one that should be used, and is unique. 8 | # 9 | # This file is up-to-date if the command git log --format="%aN <%aE>" | sort -u 10 | # gives no duplicates. 11 | 12 | Tralah M Brian TralahM 13 | 14 | -------------------------------------------------------------------------------- /Custom_Firebase_Database_Backend.md: -------------------------------------------------------------------------------- 1 | What does the database backend do? It sits between the Django ORM and the actual database driver. There’s a PEP249, the DB-API 2.0 specification for python code to talk to the actual database driver. 2 | 3 | Django abstracts away many of the differences between databases. But not all databases are created equal, so sometimes supporting what django expects is hard. Michael maintains the microsoft sql backend and showed some of the differences. 4 | 5 | 6 | 7 | If you need a custom database backend, you could subclass an existing django database backend. There’s a read-only postgres db backend that has only a few lines of code. But if you create one from scratch, you need to implement about 8 classes. 8 | 9 | - The **DatabaseWrapper** talks to the PEP249 python database library. Important: the “vendor” string to help django do specific things when it uses your database. 10 | column types,lookup and pattern operators 11 | There are other attributes that tell django how to map simple queries to actual SQL. iexact, less than, stuff like that. 12 | 13 | - **CursorWrapper**. This one wraps the database cursor. So it tranlates execute, executemany, fetchone, fetchmany, fetchall, etc., to how the database talks. 14 | - **CursorDebugWrapper** : the same as above, only it adds timing information 15 | and logging everywhere. Django uses it in DEBUG mode. 16 | 17 | - **DatabaseFeatures**: a list of features that the database supports. It is mainly used to automatically exclude/include tests from django’s testcase. 18 | how NULL Ordering works, SELECT FOR, 19 | - **DatabaseSchemaEditor** : used by the migration mechanism to change your database schema. Altering a field is complex. 20 | - **DatabaseIntrospection**. Used by the inspectdb management command. For his mssql database backend, it is important functionality. It is used relatively often. 21 | - **DatabaseValidation** : this hooks the backend into django’s upon-startup validation mechanism. 22 | - **DatabaseOperations** is where various bits and pieces that didn’t fit elsewhere went. A big part: date and time helpers. 23 | type casting and value extractions 24 | 25 | There’s more than these classes, though. 26 | 27 | If you make a query, in the end the .as_sql() method is called on an “sql compiler”. For a custom database backend, you might need to do customization here. Internally, django seems to prefer Postgresql’s sql style. 28 | 29 | You need to look at database-specific ways in which you could do database injection. And catch it. 30 | 31 | You need custom tests. And you’ll sometimes need to monkeypatch existing tests with @expectedFailure. But the good thing is that there’s a huge amount of existing tests that will be run on your database. 32 | 33 | # Down the Rabbit Hole 34 | 1. Models 35 | 2. Managers 36 | 3. Queryset 37 | 4. Query 38 | Data structure and methods representing a database query 39 | Lives in django.db.models.sql 40 | Two flavours: **Query** normal ORM operations and **RawQuery** for raw() 41 | 5. SQLCompiler 42 | Turns Django Query instances into SQL for your database, Subclasses for 43 | non-SELECT queries: SQLInsertCompiler and SQLDeleteCompiler for INSERT and 44 | DELETE respectively 45 | 6. Database Backend 46 | ## Database Backend 47 | - Base Implemetation,plus one per supported database (built-in ones in 48 | django.db.models.backends) 49 | 50 | - Goes in the ENGINE part of database settings 51 | - Specifies extremely low-level behaviour 52 | - Is the boundary between Django and the Database drivers 53 | (psycopg2,cx_Oracle,etc.) 54 | 55 | 56 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | GNU GENERAL PUBLIC LICENSE 3 | Version 3, 29 June 2007 4 | 5 | Copyright (C) 2007 Free Software Foundation, Inc. 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The GNU General Public License is a free, copyleft license for 12 | software and other kinds of works. 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 | the GNU General Public License is 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. We, the Free Software Foundation, use the 19 | GNU General Public License for most of our software; it applies also to 20 | any other work released this way by its authors. You can apply it to 21 | your programs, too. 22 | 23 | When we speak of free software, we are referring to freedom, not 24 | price. Our General Public Licenses are designed to make sure that you 25 | have the freedom to distribute copies of free software (and charge for 26 | them if you wish), that you receive source code or can get it if you 27 | want it, that you can change the software or use pieces of it in new 28 | free programs, and that you know you can do these things. 29 | 30 | To protect your rights, we need to prevent others from denying you 31 | these rights or asking you to surrender the rights. Therefore, you have 32 | certain responsibilities if you distribute copies of the software, or if 33 | you modify it: responsibilities to respect the freedom of others. 34 | 35 | For example, if you distribute copies of such a program, whether 36 | gratis or for a fee, you must pass on to the recipients the same 37 | freedoms that you received. You must make sure that they, too, receive 38 | or can get the source code. And you must show them these terms so they 39 | know their rights. 40 | 41 | Developers that use the GNU GPL protect your rights with two steps: 42 | (1) assert copyright on the software, and (2) offer you this License 43 | giving you legal permission to copy, distribute and/or modify it. 44 | 45 | For the developers' and authors' protection, the GPL clearly explains 46 | that there is no warranty for this free software. For both users' and 47 | authors' sake, the GPL requires that modified versions be marked as 48 | changed, so that their problems will not be attributed erroneously to 49 | authors of previous versions. 50 | 51 | Some devices are designed to deny users access to install or run 52 | modified versions of the software inside them, although the manufacturer 53 | can do so. This is fundamentally incompatible with the aim of 54 | protecting users' freedom to change the software. The systematic 55 | pattern of such abuse occurs in the area of products for individuals to 56 | use, which is precisely where it is most unacceptable. Therefore, we 57 | have designed this version of the GPL to prohibit the practice for those 58 | products. If such problems arise substantially in other domains, we 59 | stand ready to extend this provision to those domains in future versions 60 | of the GPL, as needed to protect the freedom of users. 61 | 62 | Finally, every program is threatened constantly by software patents. 63 | States should not allow patents to restrict development and use of 64 | software on general-purpose computers, but in those that do, we wish to 65 | avoid the special danger that patents applied to a free program could 66 | make it effectively proprietary. To prevent this, the GPL assures that 67 | patents cannot be used to render the program non-free. 68 | 69 | The precise terms and conditions for copying, distribution and 70 | modification follow. 71 | 72 | TERMS AND CONDITIONS 73 | 74 | 0. Definitions. 75 | 76 | "This License" refers to version 3 of the GNU General Public License. 77 | 78 | "Copyright" also means copyright-like laws that apply to other kinds of 79 | works, such as semiconductor masks. 80 | 81 | "The Program" refers to any copyrightable work licensed under this 82 | License. Each licensee is addressed as "you". "Licensees" and 83 | "recipients" may be individuals or organizations. 84 | 85 | To "modify" a work means to copy from or adapt all or part of the work 86 | in a fashion requiring copyright permission, other than the making of an 87 | exact copy. The resulting work is called a "modified version" of the 88 | earlier work or a work "based on" the earlier work. 89 | 90 | A "covered work" means either the unmodified Program or a work based 91 | on the Program. 92 | 93 | To "propagate" a work means to do anything with it that, without 94 | permission, would make you directly or secondarily liable for 95 | infringement under applicable copyright law, except executing it on a 96 | computer or modifying a private copy. Propagation includes copying, 97 | distribution (with or without modification), making available to the 98 | public, and in some countries other activities as well. 99 | 100 | To "convey" a work means any kind of propagation that enables other 101 | parties to make or receive copies. Mere interaction with a user through 102 | a computer network, with no transfer of a copy, is not conveying. 103 | 104 | An interactive user interface displays "Appropriate Legal Notices" 105 | to the extent that it includes a convenient and prominently visible 106 | feature that (1) displays an appropriate copyright notice, and (2) 107 | tells the user that there is no warranty for the work (except to the 108 | extent that warranties are provided), that licensees may convey the 109 | work under this License, and how to view a copy of this License. If 110 | the interface presents a list of user commands or options, such as a 111 | menu, a prominent item in the list meets this criterion. 112 | 113 | 1. Source Code. 114 | 115 | The "source code" for a work means the preferred form of the work 116 | for making modifications to it. "Object code" means any non-source 117 | form of a work. 118 | 119 | A "Standard Interface" means an interface that either is an official 120 | standard defined by a recognized standards body, or, in the case of 121 | interfaces specified for a particular programming language, one that 122 | is widely used among developers working in that language. 123 | 124 | The "System Libraries" of an executable work include anything, other 125 | than the work as a whole, that (a) is included in the normal form of 126 | packaging a Major Component, but which is not part of that Major 127 | Component, and (b) serves only to enable use of the work with that 128 | Major Component, or to implement a Standard Interface for which an 129 | implementation is available to the public in source code form. A 130 | "Major Component", in this context, means a major essential component 131 | (kernel, window system, and so on) of the specific operating system 132 | (if any) on which the executable work runs, or a compiler used to 133 | produce the work, or an object code interpreter used to run it. 134 | 135 | The "Corresponding Source" for a work in object code form means all 136 | the source code needed to generate, install, and (for an executable 137 | work) run the object code and to modify the work, including scripts to 138 | control those activities. However, it does not include the work's 139 | System Libraries, or general-purpose tools or generally available free 140 | programs which are used unmodified in performing those activities but 141 | which are not part of the work. For example, Corresponding Source 142 | includes interface definition files associated with source files for 143 | the work, and the source code for shared libraries and dynamically 144 | linked subprograms that the work is specifically designed to require, 145 | such as by intimate data communication or control flow between those 146 | subprograms and other parts of the work. 147 | 148 | The Corresponding Source need not include anything that users 149 | can regenerate automatically from other parts of the Corresponding 150 | Source. 151 | 152 | The Corresponding Source for a work in source code form is that 153 | same work. 154 | 155 | 2. Basic Permissions. 156 | 157 | All rights granted under this License are granted for the term of 158 | copyright on the Program, and are irrevocable provided the stated 159 | conditions are met. This License explicitly affirms your unlimited 160 | permission to run the unmodified Program. The output from running a 161 | covered work is covered by this License only if the output, given its 162 | content, constitutes a covered work. This License acknowledges your 163 | rights of fair use or other equivalent, as provided by copyright law. 164 | 165 | You may make, run and propagate covered works that you do not 166 | convey, without conditions so long as your license otherwise remains 167 | in force. You may convey covered works to others for the sole purpose 168 | of having them make modifications exclusively for you, or provide you 169 | with facilities for running those works, provided that you comply with 170 | the terms of this License in conveying all material for which you do 171 | not control copyright. Those thus making or running the covered works 172 | for you must do so exclusively on your behalf, under your direction 173 | and control, on terms that prohibit them from making any copies of 174 | your copyrighted material outside their relationship with you. 175 | 176 | Conveying under any other circumstances is permitted solely under 177 | the conditions stated below. Sublicensing is not allowed; section 10 178 | makes it unnecessary. 179 | 180 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 181 | 182 | No covered work shall be deemed part of an effective technological 183 | measure under any applicable law fulfilling obligations under article 184 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 185 | similar laws prohibiting or restricting circumvention of such 186 | measures. 187 | 188 | When you convey a covered work, you waive any legal power to forbid 189 | circumvention of technological measures to the extent such circumvention 190 | is effected by exercising rights under this License with respect to 191 | the covered work, and you disclaim any intention to limit operation or 192 | modification of the work as a means of enforcing, against the work's 193 | users, your or third parties' legal rights to forbid circumvention of 194 | technological measures. 195 | 196 | 4. Conveying Verbatim Copies. 197 | 198 | You may convey verbatim copies of the Program's source code as you 199 | receive it, in any medium, provided that you conspicuously and 200 | appropriately publish on each copy an appropriate copyright notice; 201 | keep intact all notices stating that this License and any 202 | non-permissive terms added in accord with section 7 apply to the code; 203 | keep intact all notices of the absence of any warranty; and give all 204 | recipients a copy of this License along with the Program. 205 | 206 | You may charge any price or no price for each copy that you convey, 207 | and you may offer support or warranty protection for a fee. 208 | 209 | 5. Conveying Modified Source Versions. 210 | 211 | You may convey a work based on the Program, or the modifications to 212 | produce it from the Program, in the form of source code under the 213 | terms of section 4, provided that you also meet all of these conditions: 214 | 215 | a) The work must carry prominent notices stating that you modified 216 | it, and giving a relevant date. 217 | 218 | b) The work must carry prominent notices stating that it is 219 | released under this License and any conditions added under section 220 | 7. This requirement modifies the requirement in section 4 to 221 | "keep intact all notices". 222 | 223 | c) You must license the entire work, as a whole, under this 224 | License to anyone who comes into possession of a copy. This 225 | License will therefore apply, along with any applicable section 7 226 | additional terms, to the whole of the work, and all its parts, 227 | regardless of how they are packaged. This License gives no 228 | permission to license the work in any other way, but it does not 229 | invalidate such permission if you have separately received it. 230 | 231 | d) If the work has interactive user interfaces, each must display 232 | Appropriate Legal Notices; however, if the Program has interactive 233 | interfaces that do not display Appropriate Legal Notices, your 234 | work need not make them do so. 235 | 236 | A compilation of a covered work with other separate and independent 237 | works, which are not by their nature extensions of the covered work, 238 | and which are not combined with it such as to form a larger program, 239 | in or on a volume of a storage or distribution medium, is called an 240 | "aggregate" if the compilation and its resulting copyright are not 241 | used to limit the access or legal rights of the compilation's users 242 | beyond what the individual works permit. Inclusion of a covered work 243 | in an aggregate does not cause this License to apply to the other 244 | parts of the aggregate. 245 | 246 | 6. Conveying Non-Source Forms. 247 | 248 | You may convey a covered work in object code form under the terms 249 | of sections 4 and 5, provided that you also convey the 250 | machine-readable Corresponding Source under the terms of this License, 251 | in one of these ways: 252 | 253 | a) Convey the object code in, or embodied in, a physical product 254 | (including a physical distribution medium), accompanied by the 255 | Corresponding Source fixed on a durable physical medium 256 | customarily used for software interchange. 257 | 258 | b) Convey the object code in, or embodied in, a physical product 259 | (including a physical distribution medium), accompanied by a 260 | written offer, valid for at least three years and valid for as 261 | long as you offer spare parts or customer support for that product 262 | model, to give anyone who possesses the object code either (1) a 263 | copy of the Corresponding Source for all the software in the 264 | product that is covered by this License, on a durable physical 265 | medium customarily used for software interchange, for a price no 266 | more than your reasonable cost of physically performing this 267 | conveying of source, or (2) access to copy the 268 | Corresponding Source from a network server at no charge. 269 | 270 | c) Convey individual copies of the object code with a copy of the 271 | written offer to provide the Corresponding Source. This 272 | alternative is allowed only occasionally and noncommercially, and 273 | only if you received the object code with such an offer, in accord 274 | with subsection 6b. 275 | 276 | d) Convey the object code by offering access from a designated 277 | place (gratis or for a charge), and offer equivalent access to the 278 | Corresponding Source in the same way through the same place at no 279 | further charge. You need not require recipients to copy the 280 | Corresponding Source along with the object code. If the place to 281 | copy the object code is a network server, the Corresponding Source 282 | may be on a different server (operated by you or a third party) 283 | that supports equivalent copying facilities, provided you maintain 284 | clear directions next to the object code saying where to find the 285 | Corresponding Source. Regardless of what server hosts the 286 | Corresponding Source, you remain obligated to ensure that it is 287 | available for as long as needed to satisfy these requirements. 288 | 289 | e) Convey the object code using peer-to-peer transmission, provided 290 | you inform other peers where the object code and Corresponding 291 | Source of the work are being offered to the general public at no 292 | charge under subsection 6d. 293 | 294 | A separable portion of the object code, whose source code is excluded 295 | from the Corresponding Source as a System Library, need not be 296 | included in conveying the object code work. 297 | 298 | A "User Product" is either (1) a "consumer product", which means any 299 | tangible personal property which is normally used for personal, family, 300 | or household purposes, or (2) anything designed or sold for incorporation 301 | into a dwelling. In determining whether a product is a consumer product, 302 | doubtful cases shall be resolved in favor of coverage. For a particular 303 | product received by a particular user, "normally used" refers to a 304 | typical or common use of that class of product, regardless of the status 305 | of the particular user or of the way in which the particular user 306 | actually uses, or expects or is expected to use, the product. A product 307 | is a consumer product regardless of whether the product has substantial 308 | commercial, industrial or non-consumer uses, unless such uses represent 309 | the only significant mode of use of the product. 310 | 311 | "Installation Information" for a User Product means any methods, 312 | procedures, authorization keys, or other information required to install 313 | and execute modified versions of a covered work in that User Product from 314 | a modified version of its Corresponding Source. The information must 315 | suffice to ensure that the continued functioning of the modified object 316 | code is in no case prevented or interfered with solely because 317 | modification has been made. 318 | 319 | If you convey an object code work under this section in, or with, or 320 | specifically for use in, a User Product, and the conveying occurs as 321 | part of a transaction in which the right of possession and use of the 322 | User Product is transferred to the recipient in perpetuity or for a 323 | fixed term (regardless of how the transaction is characterized), the 324 | Corresponding Source conveyed under this section must be accompanied 325 | by the Installation Information. But this requirement does not apply 326 | if neither you nor any third party retains the ability to install 327 | modified object code on the User Product (for example, the work has 328 | been installed in ROM). 329 | 330 | The requirement to provide Installation Information does not include a 331 | requirement to continue to provide support service, warranty, or updates 332 | for a work that has been modified or installed by the recipient, or for 333 | the User Product in which it has been modified or installed. Access to a 334 | network may be denied when the modification itself materially and 335 | adversely affects the operation of the network or violates the rules and 336 | protocols for communication across the network. 337 | 338 | Corresponding Source conveyed, and Installation Information provided, 339 | in accord with this section must be in a format that is publicly 340 | documented (and with an implementation available to the public in 341 | source code form), and must require no special password or key for 342 | unpacking, reading or copying. 343 | 344 | 7. Additional Terms. 345 | 346 | "Additional permissions" are terms that supplement the terms of this 347 | License by making exceptions from one or more of its conditions. 348 | Additional permissions that are applicable to the entire Program shall 349 | be treated as though they were included in this License, to the extent 350 | that they are valid under applicable law. If additional permissions 351 | apply only to part of the Program, that part may be used separately 352 | under those permissions, but the entire Program remains governed by 353 | this License without regard to the additional permissions. 354 | 355 | When you convey a copy of a covered work, you may at your option 356 | remove any additional permissions from that copy, or from any part of 357 | it. (Additional permissions may be written to require their own 358 | removal in certain cases when you modify the work.) You may place 359 | additional permissions on material, added by you to a covered work, 360 | for which you have or can give appropriate copyright permission. 361 | 362 | Notwithstanding any other provision of this License, for material you 363 | add to a covered work, you may (if authorized by the copyright holders of 364 | that material) supplement the terms of this License with terms: 365 | 366 | a) Disclaiming warranty or limiting liability differently from the 367 | terms of sections 15 and 16 of this License; or 368 | 369 | b) Requiring preservation of specified reasonable legal notices or 370 | author attributions in that material or in the Appropriate Legal 371 | Notices displayed by works containing it; or 372 | 373 | c) Prohibiting misrepresentation of the origin of that material, or 374 | requiring that modified versions of such material be marked in 375 | reasonable ways as different from the original version; or 376 | 377 | d) Limiting the use for publicity purposes of names of licensors or 378 | authors of the material; or 379 | 380 | e) Declining to grant rights under trademark law for use of some 381 | trade names, trademarks, or service marks; or 382 | 383 | f) Requiring indemnification of licensors and authors of that 384 | material by anyone who conveys the material (or modified versions of 385 | it) with contractual assumptions of liability to the recipient, for 386 | any liability that these contractual assumptions directly impose on 387 | those licensors and authors. 388 | 389 | All other non-permissive additional terms are considered "further 390 | restrictions" within the meaning of section 10. If the Program as you 391 | received it, or any part of it, contains a notice stating that it is 392 | governed by this License along with a term that is a further 393 | restriction, you may remove that term. If a license document contains 394 | a further restriction but permits relicensing or conveying under this 395 | License, you may add to a covered work material governed by the terms 396 | of that license document, provided that the further restriction does 397 | not survive such relicensing or conveying. 398 | 399 | If you add terms to a covered work in accord with this section, you 400 | must place, in the relevant source files, a statement of the 401 | additional terms that apply to those files, or a notice indicating 402 | where to find the applicable terms. 403 | 404 | Additional terms, permissive or non-permissive, may be stated in the 405 | form of a separately written license, or stated as exceptions; 406 | the above requirements apply either way. 407 | 408 | 8. Termination. 409 | 410 | You may not propagate or modify a covered work except as expressly 411 | provided under this License. Any attempt otherwise to propagate or 412 | modify it is void, and will automatically terminate your rights under 413 | this License (including any patent licenses granted under the third 414 | paragraph of section 11). 415 | 416 | However, if you cease all violation of this License, then your 417 | license from a particular copyright holder is reinstated (a) 418 | provisionally, unless and until the copyright holder explicitly and 419 | finally terminates your license, and (b) permanently, if the copyright 420 | holder fails to notify you of the violation by some reasonable means 421 | prior to 60 days after the cessation. 422 | 423 | Moreover, your license from a particular copyright holder is 424 | reinstated permanently if the copyright holder notifies you of the 425 | violation by some reasonable means, this is the first time you have 426 | received notice of violation of this License (for any work) from that 427 | copyright holder, and you cure the violation prior to 30 days after 428 | your receipt of the notice. 429 | 430 | Termination of your rights under this section does not terminate the 431 | licenses of parties who have received copies or rights from you under 432 | this License. If your rights have been terminated and not permanently 433 | reinstated, you do not qualify to receive new licenses for the same 434 | material under section 10. 435 | 436 | 9. Acceptance Not Required for Having Copies. 437 | 438 | You are not required to accept this License in order to receive or 439 | run a copy of the Program. Ancillary propagation of a covered work 440 | occurring solely as a consequence of using peer-to-peer transmission 441 | to receive a copy likewise does not require acceptance. However, 442 | nothing other than this License grants you permission to propagate or 443 | modify any covered work. These actions infringe copyright if you do 444 | not accept this License. Therefore, by modifying or propagating a 445 | covered work, you indicate your acceptance of this License to do so. 446 | 447 | 10. Automatic Licensing of Downstream Recipients. 448 | 449 | Each time you convey a covered work, the recipient automatically 450 | receives a license from the original licensors, to run, modify and 451 | propagate that work, subject to this License. You are not responsible 452 | for enforcing compliance by third parties with this License. 453 | 454 | An "entity transaction" is a transaction transferring control of an 455 | organization, or substantially all assets of one, or subdividing an 456 | organization, or merging organizations. If propagation of a covered 457 | work results from an entity transaction, each party to that 458 | transaction who receives a copy of the work also receives whatever 459 | licenses to the work the party's predecessor in interest had or could 460 | give under the previous paragraph, plus a right to possession of the 461 | Corresponding Source of the work from the predecessor in interest, if 462 | the predecessor has it or can get it with reasonable efforts. 463 | 464 | You may not impose any further restrictions on the exercise of the 465 | rights granted or affirmed under this License. For example, you may 466 | not impose a license fee, royalty, or other charge for exercise of 467 | rights granted under this License, and you may not initiate litigation 468 | (including a cross-claim or counterclaim in a lawsuit) alleging that 469 | any patent claim is infringed by making, using, selling, offering for 470 | sale, or importing the Program or any portion of it. 471 | 472 | 11. Patents. 473 | 474 | A "contributor" is a copyright holder who authorizes use under this 475 | License of the Program or a work on which the Program is based. The 476 | work thus licensed is called the contributor's "contributor version". 477 | 478 | A contributor's "essential patent claims" are all patent claims 479 | owned or controlled by the contributor, whether already acquired or 480 | hereafter acquired, that would be infringed by some manner, permitted 481 | by this License, of making, using, or selling its contributor version, 482 | but do not include claims that would be infringed only as a 483 | consequence of further modification of the contributor version. For 484 | purposes of this definition, "control" includes the right to grant 485 | patent sublicenses in a manner consistent with the requirements of 486 | this License. 487 | 488 | Each contributor grants you a non-exclusive, worldwide, royalty-free 489 | patent license under the contributor's essential patent claims, to 490 | make, use, sell, offer for sale, import and otherwise run, modify and 491 | propagate the contents of its contributor version. 492 | 493 | In the following three paragraphs, a "patent license" is any express 494 | agreement or commitment, however denominated, not to enforce a patent 495 | (such as an express permission to practice a patent or covenant not to 496 | sue for patent infringement). To "grant" such a patent license to a 497 | party means to make such an agreement or commitment not to enforce a 498 | patent against the party. 499 | 500 | If you convey a covered work, knowingly relying on a patent license, 501 | and the Corresponding Source of the work is not available for anyone 502 | to copy, free of charge and under the terms of this License, through a 503 | publicly available network server or other readily accessible means, 504 | then you must either (1) cause the Corresponding Source to be so 505 | available, or (2) arrange to deprive yourself of the benefit of the 506 | patent license for this particular work, or (3) arrange, in a manner 507 | consistent with the requirements of this License, to extend the patent 508 | license to downstream recipients. "Knowingly relying" means you have 509 | actual knowledge that, but for the patent license, your conveying the 510 | covered work in a country, or your recipient's use of the covered work 511 | in a country, would infringe one or more identifiable patents in that 512 | country that you have reason to believe are valid. 513 | 514 | If, pursuant to or in connection with a single transaction or 515 | arrangement, you convey, or propagate by procuring conveyance of, a 516 | covered work, and grant a patent license to some of the parties 517 | receiving the covered work authorizing them to use, propagate, modify 518 | or convey a specific copy of the covered work, then the patent license 519 | you grant is automatically extended to all recipients of the covered 520 | work and works based on it. 521 | 522 | A patent license is "discriminatory" if it does not include within 523 | the scope of its coverage, prohibits the exercise of, or is 524 | conditioned on the non-exercise of one or more of the rights that are 525 | specifically granted under this License. You may not convey a covered 526 | work if you are a party to an arrangement with a third party that is 527 | in the business of distributing software, under which you make payment 528 | to the third party based on the extent of your activity of conveying 529 | the work, and under which the third party grants, to any of the 530 | parties who would receive the covered work from you, a discriminatory 531 | patent license (a) in connection with copies of the covered work 532 | conveyed by you (or copies made from those copies), or (b) primarily 533 | for and in connection with specific products or compilations that 534 | contain the covered work, unless you entered into that arrangement, 535 | or that patent license was granted, prior to 28 March 2007. 536 | 537 | Nothing in this License shall be construed as excluding or limiting 538 | any implied license or other defenses to infringement that may 539 | otherwise be available to you under applicable patent law. 540 | 541 | 12. No Surrender of Others' Freedom. 542 | 543 | If conditions are imposed on you (whether by court order, agreement or 544 | otherwise) that contradict the conditions of this License, they do not 545 | excuse you from the conditions of this License. If you cannot convey a 546 | covered work so as to satisfy simultaneously your obligations under this 547 | License and any other pertinent obligations, then as a consequence you may 548 | not convey it at all. For example, if you agree to terms that obligate you 549 | to collect a royalty for further conveying from those to whom you convey 550 | the Program, the only way you could satisfy both those terms and this 551 | License would be to refrain entirely from conveying the Program. 552 | 553 | 13. Use with the GNU Affero General Public License. 554 | 555 | Notwithstanding any other provision of this License, you have 556 | permission to link or combine any covered work with a work licensed 557 | under version 3 of the GNU Affero General Public License into a single 558 | combined work, and to convey the resulting work. The terms of this 559 | License will continue to apply to the part which is the covered work, 560 | but the special requirements of the GNU Affero General Public License, 561 | section 13, concerning interaction through a network will apply to the 562 | combination as such. 563 | 564 | 14. Revised Versions of this License. 565 | 566 | The Free Software Foundation may publish revised and/or new versions of 567 | the GNU General Public License from time to time. Such new versions will 568 | be similar in spirit to the present version, but may differ in detail to 569 | address new problems or concerns. 570 | 571 | Each version is given a distinguishing version number. If the 572 | Program specifies that a certain numbered version of the GNU General 573 | Public License "or any later version" applies to it, you have the 574 | option of following the terms and conditions either of that numbered 575 | version or of any later version published by the Free Software 576 | Foundation. If the Program does not specify a version number of the 577 | GNU General Public License, you may choose any version ever published 578 | by the Free Software Foundation. 579 | 580 | If the Program specifies that a proxy can decide which future 581 | versions of the GNU General Public License can be used, that proxy's 582 | public statement of acceptance of a version permanently authorizes you 583 | to choose that version for the Program. 584 | 585 | Later license versions may give you additional or different 586 | permissions. However, no additional obligations are imposed on any 587 | author or copyright holder as a result of your choosing to follow a 588 | later version. 589 | 590 | 15. Disclaimer of Warranty. 591 | 592 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 593 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 594 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 595 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 596 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 597 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 598 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 599 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 600 | 601 | 16. Limitation of Liability. 602 | 603 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 604 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 605 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 606 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 607 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 608 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 609 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 610 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 611 | SUCH DAMAGES. 612 | 613 | 17. Interpretation of Sections 15 and 16. 614 | 615 | If the disclaimer of warranty and limitation of liability provided 616 | above cannot be given local legal effect according to their terms, 617 | reviewing courts shall apply local law that most closely approximates 618 | an absolute waiver of all civil liability in connection with the 619 | Program, unless a warranty or assumption of liability accompanies a 620 | copy of the Program in return for a fee. 621 | 622 | END OF TERMS AND CONDITIONS 623 | 624 | How to Apply These Terms to Your New Programs 625 | 626 | If you develop a new program, and you want it to be of the greatest 627 | possible use to the public, the best way to achieve this is to make it 628 | free software which everyone can redistribute and change under these terms. 629 | 630 | To do so, attach the following notices to the program. It is safest 631 | to attach them to the start of each source file to most effectively 632 | state the exclusion of warranty; and each file should have at least 633 | the "copyright" line and a pointer to where the full notice is found. 634 | 635 | 636 | Copyright (C) 637 | 638 | This program is free software: you can redistribute it and/or modify 639 | it under the terms of the GNU General Public License as published by 640 | the Free Software Foundation, either version 3 of the License, or 641 | (at your option) any later version. 642 | 643 | This program is distributed in the hope that it will be useful, 644 | but WITHOUT ANY WARRANTY; without even the implied warranty of 645 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 646 | GNU General Public License for more details. 647 | 648 | You should have received a copy of the GNU General Public License 649 | along with this program. If not, see . 650 | 651 | Also add information on how to contact you by electronic and paper mail. 652 | 653 | If the program does terminal interaction, make it output a short 654 | notice like this when it starts in an interactive mode: 655 | 656 | Copyright (C) 657 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 658 | This is free software, and you are welcome to redistribute it 659 | under certain conditions; type `show c' for details. 660 | 661 | The hypothetical commands `show w' and `show c' should show the appropriate 662 | parts of the General Public License. Of course, your program's commands 663 | might be different; for a GUI interface, you would use an "about box". 664 | 665 | You should also get your employer (if you work as a programmer) or school, 666 | if any, to sign a "copyright disclaimer" for the program, if necessary. 667 | For more information on this, and how to apply and follow the GNU GPL, see 668 | . 669 | 670 | The GNU General Public License does not permit incorporating your program 671 | into proprietary programs. If your program is a subroutine library, you 672 | may consider it more useful to permit linking proprietary applications with 673 | the library. If this is what you want to do, use the GNU Lesser General 674 | Public License instead of this License. But first, please read 675 | . 676 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | [![Build Status](https://travis-ci.com/TralahM/django-firebase-orm.svg?branch=master)](https://travis-ci.com/TralahM/django-firebase-orm) 3 | [![Build status](https://ci.appveyor.com/api/projects/status/yvvmq5hyf7hj743a/branch/master?svg=true)](https://ci.appveyor.com/project/TralahM/django-firebase-orm/branch/master) 4 | [![Documentation Status](https://readthedocs.org/projects/django-firebase-orm/badge/?version=latest)](https://django-firebase-orm.readthedocs.io/en/latest/?badge=latest) 5 | [![License: GPLv3](https://img.shields.io/badge/License-GPLV2-green.svg)](https://opensource.org/licenses/GPLV2) 6 | [![Organization](https://img.shields.io/badge/Org-TralahTek-blue.svg)](https://github.com/TralahTek) 7 | [![Views](http://hits.dwyl.io/TralahM/django-firebase-orm.svg)](http://dwyl.io/TralahM/django-firebase-orm) 8 | [![PRs Welcome](https://img.shields.io/badge/PRs-Welcome-brightgreen.svg?style=flat-square)](https://github.com/TralahM/django-firebase-orm/pull/) 9 | [![GitHub pull-requests](https://img.shields.io/badge/Issues-pr-red.svg?style=flat-square)](https://github.com/TralahM/django-firebase-orm/pull/) 10 | [![Language](https://img.shields.io/badge/Language-python-3572A5.svg)](https://github.com/TralahM) 11 | 12 | 13 | 14 | 15 | # django-firebase-orm. 16 | 17 | Django like models for NoSQL database Firestore Integrating with 18 | django\'s ORM. This is a fork and improvement of 19 | [firebase_orm](https://github.com/joewalk102/firebase-orm) project which 20 | was initially forked from [xavx0z](https://github.com/xavx0z) and 21 | stopped maintaining it. 22 | 23 | I made a few changes and improvements to suit my liking: 24 | 25 | 1. Changed the need of creating a second settings.py file in the root 26 | of your django project to now only require that you define the 27 | neccessary configurations in your project\'s settings module. *Note 28 | that django is now an explicit dependency* 29 | 2. Created a new package for this app on pypi under 30 | **django-firebase-orm** 31 | 32 | It is my desire to continue the development of this project and thus 33 | welcome all developers wishing to contribute via improving 34 | documentation, bug fixes, test coverage, new features, etc. 35 | 36 | Installation 37 | ------------ 38 | 39 | ```shell 40 | $ pip install django-firebase-orm 41 | ``` 42 | 43 | Initialize 44 | ---------- 45 | 46 | In your project settings add the following configuration variables 47 | 48 | > settings.py 49 | > 50 | ```python 51 | FIREBASE_ORM_CERTIFICATE = 'path/to/serviceAccountKey.json' 52 | FIREBASE_ORM_BUCKET_NAME = '.appspot.com' 53 | ``` 54 | 55 | FIREBASE_ORM_CERTIFICATE 56 | 57 | : Once you have created a [Firebase 58 | console](https://console.firebase.google.com/?authuser=0) project 59 | and downloaded a JSON file with your service account credentials. 60 | 61 | FIREBASE_ORM_BUCKET_NAME 62 | 63 | : The bucket name must not contain gs:// or any other protocol 64 | prefixes. For example, if the bucket URL displayed in the [Firebase 65 | console](https://console.firebase.google.com/?authuser=0) is 66 | gs://bucket-name.appspot.com, pass the string 67 | bucket-name.appspot.com 68 | 69 | Usage 70 | ----- 71 | 72 | ### Create model: 73 | 74 | ```python 75 | from firebase_orm import models 76 | 77 | 78 | class Article(models.Model): 79 | headline = models.TextField() 80 | type_article = models.TextField(db_column='type') 81 | 82 | class Meta: 83 | db_table = 'medications' 84 | 85 | def __str__(self): 86 | return self.headline 87 | ``` 88 | 89 | ### Using The API: 90 | 91 | **Creating objects** 92 | 93 | To represent cloud firestore data in Python objects, FirebaseORM uses an 94 | intuitive system: A *model* *class* represents a *collection*, and an 95 | *instance* of that class represents a *document* in collection. 96 | 97 | To create an object, instantiate it using keyword arguments to the model 98 | class, then call save() to save it to the database. 99 | 100 | ```pycon 101 | # Import the models we created 102 | >>> from models import Article 103 | # Create a new Article. 104 | >>> a = Article(headline='Django is cool') 105 | # Save the object into the database. You have to call save() explicitly. 106 | >>> a.save() 107 | ``` 108 | 109 | **Retrieving all objects** 110 | 111 | The simplest way to retrieve documents from a collections is to get all 112 | of them. To do this, use the all() method on a Manager as you would in 113 | normal django: 114 | 115 | ```pycon 116 | >>> all_Article = Article.objects.all() 117 | ``` 118 | 119 | The all() method returns a list instance Article of all the collection 120 | in the database. 121 | 122 | ```pycon 123 | # Now it has an ID. 124 | >>> a.id 125 | 1 126 | # Fields are represented as attributes on the Python object. 127 | >>> a.headline 128 | 'Django is cool' 129 | ``` 130 | 131 | **Saving changes to objects** 132 | 133 | To save changes to an object that's already in the database, use save(). 134 | 135 | Given a Article instance a that has already been saved to the database, 136 | this example changes its name and updates its record in the database: 137 | 138 | ```pycon 139 | >>> a.headline = 'Django-Firebase-ORM is awesome' 140 | >>> a.save() 141 | ``` 142 | 143 | This performs an document.update() method behind the scenes. FirebaseORM 144 | doesn't hit the database until you explicitly call save(). 145 | 146 | ```pycon 147 | # Firebase ORM provides a rich database lookup API. 148 | >>> Article.objects.get(id=1) 149 | 150 | >>> Article.objects.get(id=2) 151 | Traceback (most recent call last): 152 | ... 153 | DoesNotExist: Article matching query does not exist. 154 | ``` 155 | 156 | Field options: 157 | -------------- 158 | 159 | The following arguments are available to all field types. All are 160 | optional. 161 | 162 | **Field.db_column** 163 | 164 | > If contains characters that aren't allowed in Python variable names -- 165 | > use db_column. The name of the firestore key in document to use for 166 | > this field. If this isn't given, FirebaseORM will use the field's 167 | > name. 168 | 169 | Field types: 170 | ------------ 171 | 172 | ### AutoField 173 | 174 | **class AutoField()** 175 | 176 | > By default, FirebaseORM gives each model the following field: 177 | > 178 | 179 | ```python 180 | id = models.AutoField(primary_key=True) 181 | ``` 182 | 183 | ### TextField 184 | 185 | **class TextField(**options)\*\* 186 | 187 | > Text string Up to 1,048,487 bytes (1 MiB - 89 bytes). Only the first 188 | > 1,500 bytes of the UTF-8 representation are considered by queries. 189 | > 190 | > TextField has not extra required argument. 191 | 192 | Dependencies 193 | ------------ 194 | 195 | 1. *firebase-admin* 196 | 2. *grpcio* 197 | 3. *django* 198 | 199 | ## Building from Source for Developers 200 | 201 | ```console 202 | $ git clone https://github.com/TralahM/django-firebase-orm.git 203 | $ cd django-firebase-orm 204 | ``` 205 | 206 | # Contributing 207 | [See the Contributing File](CONTRIBUTING.rst) 208 | 209 | 210 | [See the Pull Request File](PULL_REQUEST_TEMPLATE.md) 211 | 212 | # LICENCE 213 | 214 | [Read the license here](LICENSE) 215 | 216 | CREDITS 217 | ------- 218 | 219 | Thanks to [joewalk102](https://github.com/joewalk102) for forking the 220 | original project without whom this project would not be possible. 221 | 222 | [![TralahTek](https://img.shields.io/badge/Organization-TralahTek-black.svg?style=for-the-badge&logo=github)](https://github.com/TralahTek) 223 | [![TralahM](https://img.shields.io/badge/Engineer-TralahM-blue.svg?style=for-the-badge&logo=github)](https://github.com/TralahM) 224 | [![TralahM](https://img.shields.io/badge/Maintainer-TralahM-green.svg?style=for-the-badge&logo=github)](https://github.com/TralahM) 225 | 226 | 227 | # Self-Promotion 228 | 229 | [![](https://img.shields.io/badge/Github-TralahM-green?style=for-the-badge&logo=github)](https://github.com/TralahM) 230 | [![](https://img.shields.io/badge/Twitter-%40tralahtek-red?style=for-the-badge&logo=twitter)](https://twitter.com/TralahM) 231 | [![TralahM](https://img.shields.io/badge/Kaggle-TralahM-purple.svg?style=for-the-badge&logo=kaggle)](https://kaggle.com/TralahM) 232 | [![TralahM](https://img.shields.io/badge/LinkedIn-TralahM-red.svg?style=for-the-badge&logo=linkedin)](https://linkedin.com/in/TralahM) 233 | 234 | 235 | [![Blog](https://img.shields.io/badge/Blog-tralahm.tralahtek.com-blue.svg?style=for-the-badge&logo=rss)](https://tralahm.tralahtek.com) 236 | 237 | [![TralahTek](https://img.shields.io/badge/Organization-TralahTek-cyan.svg?style=for-the-badge)](https://org.tralahtek.com) 238 | 239 | 240 | -------------------------------------------------------------------------------- /firebase_orm/__init__.py: -------------------------------------------------------------------------------- 1 | """firebase_orm package.""" 2 | __version__ = "0.6.1" 3 | -------------------------------------------------------------------------------- /firebase_orm/exceptions.py: -------------------------------------------------------------------------------- 1 | class DoesNotExist(Exception): 2 | """Reporter matching query does not exist.""" 3 | 4 | pass 5 | 6 | 7 | class CanNotBeChanged(Exception): 8 | pass 9 | 10 | 11 | class NetworkTimeOut(Exception): 12 | pass 13 | -------------------------------------------------------------------------------- /firebase_orm/models/__init__.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | from django.core.exceptions import ImproperlyConfigured 3 | from firebase_orm.models.fields import * 4 | from firebase_orm.models.base import Model 5 | from firebase_orm.models.manager import Manager 6 | 7 | import firebase_admin 8 | from firebase_admin import storage, firestore 9 | 10 | CERTIFICATE = getattr(settings, "FIREBASE_ORM_CERTIFICATE", None) 11 | BUCKET_NAME = getattr(settings, "FIREBASE_ORM_BUCKET_NAME", None) 12 | 13 | if CERTIFICATE is None: 14 | raise ImproperlyConfigured( 15 | "You havent set the FIREBASE_ORM_CERTIFICATE in your settings.py" 16 | ) 17 | if BUCKET_NAME is None: 18 | raise ImproperlyConfigured( 19 | "You havent set the FIREBASE_ORM_BUCKET_NAME in your settings.py" 20 | ) 21 | 22 | firebase_admin.initialize_app( 23 | firebase_admin.credentials.Certificate(CERTIFICATE), {"storageBucket": BUCKET_NAME} 24 | ) 25 | 26 | if not Manager.db: 27 | Manager.db = firebase_admin.firestore.client() 28 | Manager.bucket = firebase_admin.storage.bucket() 29 | -------------------------------------------------------------------------------- /firebase_orm/models/base.py: -------------------------------------------------------------------------------- 1 | from firebase_orm.models.manager import Manager 2 | from firebase_orm.models.fields import Field, AutoField 3 | 4 | 5 | class ModelBase(type): 6 | """Metaclass for all models.""" 7 | 8 | def __new__(cls, name, bases, attrs): 9 | super_new = super().__new__ 10 | parents = [b for b in bases if isinstance(b, ModelBase)] 11 | if not parents: 12 | return super_new(cls, name, bases, attrs) 13 | 14 | attrs["objects"] = Manager() 15 | attrs["id"] = AutoField() 16 | return super_new(cls, name, bases, attrs) 17 | 18 | def __init__(self, name, bases, attrs): 19 | parents = [b for b in bases if isinstance(b, ModelBase)] 20 | if not parents: 21 | return 22 | 23 | # добавление класса модели в менеджер 24 | manager = attrs["objects"] 25 | manager._model = self 26 | 27 | # установка дескрипторам полей имени колонки в базе данных 28 | for key in attrs: 29 | data = attrs[key] 30 | if issubclass(type(data), Field) and not attrs.get(key).db_column: 31 | setattr(data, "db_column", key) 32 | type.__init__(self, name, bases, attrs) 33 | 34 | 35 | class Model(metaclass=ModelBase): 36 | objects = Manager() 37 | __autoincrement = True 38 | 39 | def __init__(self, **kwargs): 40 | """все объекты и данные экземпляра хранятся в словаре self._meta""" 41 | self._meta = meta = {} 42 | """ 43 | инициализация полей модели Manager 44 | ключи - названия полей в базе данных 45 | значения - название полей модели 46 | """ 47 | model_fields = self.objects._model_fields 48 | attrs = self.__class__.__dict__ 49 | for key in attrs: 50 | val = attrs[key] 51 | if issubclass(type(val), Field): 52 | model_fields[val.__dict__.get("db_column")] = key 53 | 54 | """инициализация происходит в двух случаях 55 | 1. Создание `Model(name='any name')` 56 | - id устанавливается из автоинкремента менеджера 57 | - наполняет self._meta значениями полей, если переданы параметры в kwargs 58 | 2. Установка атрибутов из базы данных `Model.object.get(id='1')` 59 | добавление атрибутов в self._meta происходит в Manager 60 | """ 61 | if self._Model__autoincrement: 62 | # id в self._meta 63 | meta["id"] = self.objects._id_autoincrement() 64 | # kwargs в self._meta 65 | for key, value in model_fields.items(): 66 | meta[key] = kwargs.get(value) 67 | 68 | def __eq__(self, other): 69 | if self._meta == other._meta and self.Meta.db_table == other.Meta.db_table: 70 | return True 71 | 72 | def save(self): 73 | # TODO create transaction 74 | self.objects._save(self.id, self._meta) 75 | 76 | def __str__(self): 77 | return "%s object (%s)" % (self.__class__.__name__, self.id) 78 | 79 | def __repr__(self): 80 | return "<%s: %s>" % (self.__class__.__name__, self) 81 | -------------------------------------------------------------------------------- /firebase_orm/models/fields/__init__.py: -------------------------------------------------------------------------------- 1 | from firebase_orm.exceptions import CanNotBeChanged 2 | 3 | 4 | class Field: 5 | def __init__(self, db_column=None, *args, **kwargs): 6 | self.db_column = db_column 7 | 8 | def __get__(self, obj, objtype): 9 | return obj._meta.get(self.db_column) 10 | 11 | def __set__(self, obj, val): 12 | if val is None: 13 | obj._meta[self.db_column] = val 14 | elif not str(val).strip(): 15 | obj._meta[self.db_column] = None 16 | 17 | 18 | class TextField(Field): 19 | pass 20 | 21 | 22 | class AutoField: 23 | def __init__(self): 24 | self.db_column = "id" 25 | 26 | def __get__(self, obj, objtype): 27 | return obj._meta.get(self.db_column) 28 | 29 | def __set__(self, obj, val): 30 | raise CanNotBeChanged 31 | 32 | 33 | class CharField(Field): 34 | pass 35 | 36 | 37 | class DateTimeField: 38 | pass 39 | 40 | 41 | class DateField: 42 | pass 43 | 44 | 45 | class TimeField: 46 | pass 47 | 48 | 49 | class ForeignKey: 50 | pass 51 | 52 | 53 | class ManyToManyField: 54 | pass 55 | 56 | 57 | class OneToOneField: 58 | pass 59 | 60 | 61 | class UUIDField: 62 | pass 63 | 64 | 65 | class PhonenumberField(CharField): 66 | pass 67 | 68 | 69 | class DecimalField(Field): 70 | pass 71 | 72 | 73 | class IntegerField(Field): 74 | pass 75 | 76 | 77 | class FloatField(Field): 78 | pass 79 | -------------------------------------------------------------------------------- /firebase_orm/models/manager.py: -------------------------------------------------------------------------------- 1 | from firebase_orm.exceptions import DoesNotExist, NetworkTimeOut 2 | 3 | from firebase_admin import firestore 4 | import google 5 | from grpc._channel import _Rendezvous 6 | 7 | try: 8 | from settings import RETRYING_THE_REQUEST 9 | except ImportError: 10 | RETRYING_THE_REQUEST = 4 11 | 12 | 13 | retrying_the_request = 0 14 | 15 | 16 | def g_error(method_to_decorate): 17 | global retrying_the_request 18 | retrying_the_request = 0 19 | 20 | def wrapper(*args, **kwargs): 21 | try: 22 | return method_to_decorate(*args, **kwargs) 23 | 24 | except google.cloud.exceptions.NotFound: 25 | raise DoesNotExist 26 | 27 | except _Rendezvous: 28 | global retrying_the_request 29 | retrying_the_request += 1 30 | while retrying_the_request < RETRYING_THE_REQUEST: 31 | # TODO add to readme 32 | print( 33 | f"Warning: network slow or not!" 34 | f"\n Попытка подключения {retrying_the_request} из 4" 35 | ) 36 | wrapper(*args, **kwargs) 37 | raise NetworkTimeOut 38 | 39 | return wrapper 40 | 41 | 42 | class Manager: 43 | db = None 44 | rtdb = None 45 | bucket = None 46 | 47 | def __init__(self): 48 | self._model_fields = {} 49 | self._model = None 50 | 51 | @g_error 52 | def get(self, **kwargs): 53 | """ 54 | :return: Model 55 | :raise: ObjectDoesNotExist 56 | """ 57 | pk = kwargs.get("id") 58 | if not pk and pk is not 0: 59 | raise TypeError 60 | if type(pk) is not int: 61 | raise TypeError 62 | 63 | document = self._get_data(pk) 64 | 65 | return self._doc_to_instance(document) 66 | 67 | @g_error 68 | def all(self): 69 | documents = [] 70 | count = 0 71 | count_list = -1 72 | while True: 73 | docs = self._get_ref_col().offset(count).limit(10).get() 74 | for doc in docs: 75 | documents.append(doc.to_dict()) 76 | count += 1 77 | 78 | if len(documents) == count_list: 79 | break 80 | count_list = len(documents) 81 | instances = [] 82 | for document in documents: 83 | instances.append(self._doc_to_instance(document)) 84 | return instances 85 | 86 | @g_error 87 | def _id_autoincrement(self): 88 | def get_fast_id(): 89 | docs = ( 90 | self._get_ref_col() 91 | .order_by("id", direction=firestore.Query.DESCENDING) 92 | .limit(1) 93 | .get() 94 | ) 95 | for d in docs: 96 | return int(d.id) 97 | 98 | db_pk = get_fast_id() 99 | return db_pk + 1 if db_pk or db_pk is 0 else 0 100 | 101 | def _doc_to_instance(self, document): 102 | self._model._Model__autoincrement = False 103 | obj = self._model() 104 | self._model._Model__autoincrement = True 105 | 106 | obj._meta = {"id": document["id"]} 107 | # установка значений полей базы данных в model._meta 108 | for key in self._model_fields: 109 | obj._meta[key] = document.get(key) 110 | return obj 111 | 112 | def _get_data(self, pk): 113 | doc_ref = self._get_ref_doc(pk) 114 | doc = doc_ref.get() 115 | data = doc.to_dict() 116 | return data 117 | 118 | def _save(self, pk, meta): 119 | doc_ref = self._get_ref_doc(pk) 120 | doc_ref.update(meta, firestore.firestore.WriteOption()) 121 | 122 | def _get_ref_col(self): 123 | db_table = self._model.Meta.db_table 124 | return self.db.collection(db_table) 125 | 126 | def _get_ref_doc(self, pk): 127 | try: 128 | doc_ref = self._get_ref_col().document(str(pk)) 129 | except _Rendezvous: 130 | raise NetworkTimeOut 131 | return doc_ref 132 | -------------------------------------------------------------------------------- /settings.py: -------------------------------------------------------------------------------- 1 | CERTIFICATE = { 2 | "type": "service_account", 3 | "project_id": "fir-orm-python", 4 | "private_key_id": "47246fe582a99774f4daf19fad21b97a09df8c70", 5 | "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDMp79d08KEZPrn\nN0xZGULfM/eZwAJ+MytsPQhs+LVSqtx1c/oGHpQC5GiW9xwgnMpEh7xfX5NNjp6x\n0BVP9e7jS1EGcjmZqauCzYzNhnG9fuUdVQv7WmskDuCcl6sVRLjhqbSxC+xTH4pP\n+PcC19NYxqcg3DVnEHG80lXTETZmgudfUPwS92UDZK7bn1mj/skSudg2mXeRDUek\nPUtQcKD92pr2Vd/5/cvUadBKx9/IOUb0UxKPynJFKttg2iWi2oZOSgorszm6j/ms\nt9jCe5tdyyXAFV5L6wPcJ9ZBLSi3VhIwVJbq1BKC/WvbfTiwDJ5+/NifcahfuhOB\nqgH+VyePAgMBAAECggEAUMUPoK83gNr9rw1DA5MVslOnL7X5BeeaBqDb124c2eB3\nG5/HGG0vCyksIhCquDBJH9zWOmnVD/Hurcyq7KDqRChwdPPVydCN0RTgsiiScTBI\nqlfrX6six9tbSFIPglhaAy3gE1PaVEAJbWCb1DJrxgi44x4lsWRrDxOQLboIV1Iz\nEEE/GDXq4u6EoMr0pfm9nduRj+JvOO6/1EYdTkPBzX2j/UgkrY4+tYNC0dBOwjvs\n+kyUAf/Sikmzs/3TnSoGG2savtCnT+ADNYrncUsXLtaMDMX3ejmirFJHYNH7kbGk\nZsA/21wUT94WFb62NIrLOBq1Y+gn+HBLg7Etke1jgQKBgQD74Jshv8Cw/2oHdwre\nO8YDdVq8feY1p2c4ygFuJATvubMyMpA1B97KxCOuFR5YmEI5aMCFaP184EJSNFLB\nVzgs3c4T7cRwWmP9AOZUJ7SKjSC4F6uCk2XjbviFqZ7vdBKo8nbTNbg+x0dQJowE\n3b3vQArNe6z3cE7p/iGCrUYpzwKBgQDQAUaUx8bmSWL37RdQNwRodogem2nWH/Jm\nb4Th3wBfaTxT8OndDNXZSakER1kOLLO1OijfS6QWFa0U1NJM4MERlC69V3v5TeNJ\n5/b15lwgva9WsUB5YwOWrsvO0H4Ywy1WsJUPnZe/YmlpocC8EZAFRr7Wr8D4jEg7\n8/t0aJVWQQKBgQDB0xWN4wFlMydklzbFzTmTb7tjUX7Vyvyjts9i8lTaJQzAlChk\npqnLXyQV0iqIAqLziqicAS8P6YMfvyPvpC6WWBk9PLrtuqE3EHouSF+mPvPutkhF\nMyg03DBiqySjH688U1kdLzmZFcDK7N7S39BJS/8EISf5QXN4nRcseCqGAQKBgQCP\nogHiJR3k0ZJEz3SE0Kj7lbYjJIBt+vuA3sssybfRKrMc58Ql/4IAHIxYxwfo8Ndb\ncoDcyLfTBD7Tnq5lpeHMSL4Jw0p5ed5Un5h6bwr5FOLqA1YZPFUzDRrxgilA4i4B\nqcgU02cBImzWI3saoyoHarXHO/AN8ZjDxZPC66ELwQKBgQDIk+ITDLDRm6lXGiP6\nUaLRs/esyG+iNLlkQBHZtqUV+RIsde0fhpSawCHbuv9rW6hDwhn4Ojc/ml2XB0Mx\nQxkhgLIyxzyFC4AzGYi2D4WWSBpeQZyNvyWBRcLVkI3d0jW7keUPOqBuSnT+qVUw\nxpAgGdUHYiug0D4BTt8SJlyLRA==\n-----END PRIVATE KEY-----\n", 6 | "client_email": "firebase-adminsdk-bcynb@fir-orm-python.iam.gserviceaccount.com", 7 | "client_id": "103369610968201073713", 8 | "auth_uri": "https://accounts.google.com/o/oauth2/auth", 9 | "token_uri": "https://accounts.google.com/o/oauth2/token", 10 | "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", 11 | "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-bcynb%40fir-orm-python.iam.gserviceaccount.com" 12 | } 13 | 14 | BUCKET_NAME = 'fir-orm-python' 15 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | python-tag = py36 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | import firebase_orm 4 | 5 | setup( 6 | name="django-firebase-orm", 7 | version=firebase_orm.__version__, 8 | description="NoSQL object model database for django ORM integration", 9 | author="Tralah M Brian", 10 | author_email="musyoki.brian@tralahtek.com", 11 | url="https://github.com/TralahM/firebase_orm", 12 | packages=find_packages(), 13 | long_description=open("README.md").read(), 14 | long_description_content_type="text/markdown", 15 | install_requires=[ 16 | "firebase-admin==2.13.0", 17 | "grpcio>=1.9.1", 18 | "django", 19 | ], 20 | test_suite="tests", 21 | license="MIT", 22 | ) 23 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | myPath = os.path.dirname(os.path.abspath(__file__)) 5 | sys.path.insert(0, myPath + '/../') 6 | 7 | pytest_plugins = [ 8 | "orm_fixture", 9 | "firebase_fixture", 10 | "model_tests.fixture" 11 | ] 12 | -------------------------------------------------------------------------------- /tests/field_tests/id_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from firebase_orm.exceptions import CanNotBeChanged 4 | 5 | 6 | class TestAutoFieldType: 7 | def test_id_type_int(self, model): 8 | """ID должен возвращаться типа int""" 9 | inst = model.objects.get(id=0) 10 | pk = inst.id 11 | assert type(pk) is int 12 | 13 | def test_id_type_not_int(self, model): 14 | with pytest.raises(TypeError): 15 | model.objects.get(id='0') 16 | 17 | 18 | def test_present_in_the_database_document(get_document): 19 | pk = '0' 20 | doc = get_document(id=pk) 21 | assert doc.get('id') == int(pk) 22 | 23 | 24 | def test_not_change_id(model): 25 | """id не изменяемый""" 26 | with pytest.raises(CanNotBeChanged): 27 | inst = model.objects.get(id=0) 28 | inst.id = 2 29 | 30 | 31 | def test_id_unique(model, all_doc_ids): 32 | inst = model() 33 | inst.save() 34 | assert inst.id not in all_doc_ids 35 | 36 | 37 | def test_id_autoincrement(model, all_doc_ids): 38 | pk = max(all_doc_ids)+1 39 | inst = model() 40 | inst.save() 41 | assert inst.id == pk 42 | 43 | 44 | def test_pk0_if_non_existent_collection(new_collection): 45 | model = new_collection() 46 | inst = model() 47 | pk = inst.id 48 | assert pk == 0 49 | -------------------------------------------------------------------------------- /tests/firebase_fixture.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from firebase_orm.models import Manager 4 | 5 | 6 | @pytest.fixture(scope='session') 7 | def db(): 8 | d_b = Manager.db 9 | try: 10 | yield d_b 11 | finally: 12 | ids = [] 13 | count_list = -1 14 | while True: 15 | docs = d_b.collection('test').limit(4).get() 16 | for doc in docs: 17 | ids.append(doc.id) 18 | doc.reference.delete() 19 | 20 | if len(ids) == count_list: 21 | break 22 | count_list = len(ids) 23 | del ids 24 | 25 | 26 | @pytest.fixture(scope='function') 27 | def del_all(db): 28 | def del_all_in_collection(collection_name): 29 | ids = [] 30 | count_list = -1 31 | while True: 32 | docs = db.collection(collection_name).limit(4).get() 33 | for doc in docs: 34 | ids.append(doc.id) 35 | doc.reference.delete() 36 | 37 | if len(ids) == count_list: 38 | break 39 | count_list = len(ids) 40 | del ids 41 | return del_all_in_collection 42 | 43 | 44 | @pytest.fixture 45 | def add_document(db): 46 | def add_data(id, name=None, type_test=None, author=None, brief=None): 47 | doc_ref = db.collection('test').document(id) 48 | doc_ref.set({ 49 | 'id': int(id), 50 | 'name': name, 51 | 'type_test': type_test, 52 | 'author': author, 53 | 'brief': brief 54 | }) 55 | return add_data 56 | 57 | 58 | @pytest.fixture 59 | def get_document(db): 60 | def get(id): 61 | doc_ref = db.collection('test').document(id) 62 | doc = doc_ref.get().to_dict() 63 | return doc 64 | return get 65 | 66 | 67 | @pytest.fixture 68 | def all_doc_ids(db): 69 | ids = [] 70 | 71 | count = 0 72 | count_list = -1 73 | while True: 74 | docs = db.collection('test').offset(count).limit(4).get() 75 | for doc in docs: 76 | ids.append(int(doc.id)) 77 | count += 1 78 | 79 | if len(ids) == count_list: 80 | break 81 | count_list = len(ids) 82 | return ids 83 | -------------------------------------------------------------------------------- /tests/model_tests/all_test.py: -------------------------------------------------------------------------------- 1 | def test_necessary_collection(new_collection): 2 | model1 = new_collection() 3 | model2 = new_collection() 4 | for i in range(4): 5 | collection1 = model1(type_test='col1') 6 | collection1.save() 7 | collection2 = model2(type_test='col2') 8 | collection2.save() 9 | 10 | all_col_2 = model2.objects.all() 11 | types = [i.type_test for i in all_col_2] 12 | type_ = list(dict(zip(types, types)).values()) 13 | 14 | assert type_ == ['col2'] 15 | 16 | -------------------------------------------------------------------------------- /tests/model_tests/fixture.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import random 3 | import string 4 | from firebase_orm import models 5 | 6 | VOWELS = "aeiou" 7 | CONSONANTS = "".join(set(string.ascii_lowercase) - set(VOWELS)) 8 | 9 | 10 | @pytest.fixture 11 | def random_name(): 12 | def generate_word(): 13 | word = "" 14 | for i in range(8): 15 | if i % 2 == 0: 16 | word += random.choice(CONSONANTS) 17 | else: 18 | word += random.choice(VOWELS) 19 | return word 20 | 21 | return generate_word 22 | 23 | 24 | names = [] 25 | 26 | 27 | @pytest.fixture 28 | def new_collection(random_name, del_all): 29 | def return_model(): 30 | global names 31 | name = random_name() 32 | names.append(name) 33 | 34 | class Model(models.Model): 35 | type_test = models.TextField(db_column='type') 36 | 37 | class Meta: 38 | db_table = name 39 | 40 | return Model 41 | try: 42 | yield return_model 43 | finally: 44 | for i in names: 45 | del_all(i) 46 | -------------------------------------------------------------------------------- /tests/model_tests/get_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from firebase_orm.exceptions import DoesNotExist 4 | 5 | 6 | def test_error_kwarg(model): 7 | with pytest.raises(TypeError): 8 | model.objects.get(100) 9 | 10 | 11 | @pytest.mark.run(order=2) 12 | def test_get(add_document, model): 13 | pk = "0" 14 | add_document(pk) 15 | test_model = model.objects.get(id=int(pk)) 16 | assert test_model.id == int(pk) 17 | 18 | 19 | @pytest.mark.run(order=1) 20 | def test_object_does_not_exist(model): 21 | with pytest.raises(DoesNotExist): 22 | model.objects.get(id=100) 23 | -------------------------------------------------------------------------------- /tests/model_tests/model_test.py: -------------------------------------------------------------------------------- 1 | class TestEqual: 2 | 3 | def test_equal_obj(self, model): 4 | inst = model.objects.get(id=1) 5 | inst1 = model.objects.get(id=1) 6 | assert inst == inst1 7 | 8 | def test_not_equal_obj(self, model): 9 | inst = model.objects.get(id=1) 10 | inst1 = model() 11 | assert inst != inst1 12 | 13 | def test_different_models_equal(self, new_collection): 14 | model1 = new_collection() 15 | model2 = new_collection() 16 | inst1 = model1(name='name', type_test='test_type') 17 | inst1.save() 18 | inst2 = model2(name='name', type_test='test_type') 19 | inst2.save() 20 | assert inst1 != inst2 21 | 22 | 23 | def test_repr(model): 24 | inst = model.objects.get(id=1) 25 | repr_str = f'<{type(inst).__name__}: {inst.__str__()}>' 26 | assert inst.__repr__() == repr_str 27 | 28 | 29 | def test_create_with_kwargs(model): 30 | inst = model(name='test_name', type_test='test_type') 31 | pk = inst.id 32 | inst.save() 33 | inst_get = model.objects.get(id=pk) 34 | assert inst_get.type_test == 'test_type' 35 | -------------------------------------------------------------------------------- /tests/model_tests/save_test.py: -------------------------------------------------------------------------------- 1 | class TestTextStringType: 2 | def test_save_null_empty_str(self, model): 3 | """при сохранение пустой строки в поле, в базе появляется значение null""" 4 | model_null = model.objects.get(id=1) 5 | model_null.name = '' 6 | model_null.save() 7 | model_null = model.objects.get(id=1) 8 | assert model_null.name is None 9 | # TODO check the size of the data 10 | 11 | def test_save_null_str_of_spaces(self, model): 12 | """при сохранение строки с пробелами в поле, в базе появляется значение null""" 13 | model_null = model.objects.get(id=1) 14 | model_null.name = ' ' 15 | model_null.save() 16 | model_null = model.objects.get(id=1) 17 | assert model_null.name is None 18 | 19 | 20 | def test_create_inst(model): 21 | """Создание нового объекта модели""" 22 | inst = model() 23 | inst.save() 24 | pk = inst.id 25 | inst1 = model.objects.get(id=pk) 26 | assert inst == inst1 27 | -------------------------------------------------------------------------------- /tests/orm_fixture.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from firebase_orm import models 4 | 5 | 6 | class TModel(models.Model): 7 | name = models.TextField() 8 | type_test = models.TextField(db_column='type') 9 | 10 | class Meta: 11 | db_table = 'test' 12 | 13 | def __str__(self): 14 | return str(self.name) 15 | 16 | 17 | @pytest.fixture 18 | def model(): 19 | return TModel 20 | -------------------------------------------------------------------------------- /tests/pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | markers = 3 | cloud: Требует создание документов в базе данных. 4 | --------------------------------------------------------------------------------