├── .gitattributes ├── .gitignore ├── CONTRIBUTING.rst ├── LICENSE.txt ├── Procfile ├── README.rst ├── docs ├── Makefile ├── conf.py ├── index.rst ├── introduction.rst └── make.bat ├── requirements.txt ├── runtime.txt ├── setup.py └── taarifa_api ├── __init__.py ├── schemas.py ├── settings.py └── taarifa_api.py /.gitattributes: -------------------------------------------------------------------------------- 1 | # Set default behaviour, in case users don't have core.autocrlf set. 2 | * text=auto 3 | 4 | # Whitespace 5 | * whitespace=tab-in-indent,space-before-tab,trailing-space,tabwidth=2 6 | *.{py,pyx,pxd,pxi} whitespace=tab-in-indent,space-before-tab,trailing-space,tabwidth=4 7 | Makefile whitespace=space-before-tab,trailing-space,tabwidth=2 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # C extensions 4 | *.so 5 | 6 | # Packages 7 | *.egg 8 | *.egg-info 9 | dist 10 | build 11 | eggs 12 | parts 13 | bin 14 | var 15 | sdist 16 | develop-eggs 17 | .installed.cfg 18 | lib 19 | lib64 20 | .venv 21 | 22 | # Installer logs 23 | pip-log.txt 24 | 25 | # Unit test / coverage reports 26 | .coverage 27 | .tox 28 | nosetests.xml 29 | 30 | # Translations 31 | *.mo 32 | 33 | # Mr Developer 34 | .mr.developer.cfg 35 | .project 36 | .pydevproject 37 | 38 | # Sphinx 39 | _build 40 | 41 | # Heroku 42 | .env -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | Contributing to TaarifaAPI 2 | ========================== 3 | 4 | We value third-party contributions. To keep things simple for you and 5 | us, please adhere to the following contributing guidelines. 6 | 7 | Getting Started 8 | --------------- 9 | 10 | - You will need a `GitHub account`_. 11 | - Submit a `ticket for your issue `_, assuming one does not 12 | already exist. 13 | - Clearly describe the issue including steps to reproduce when it is a 14 | bug. 15 | - Make sure you specify the version that you know has the issue. 16 | - Bonus points for submitting a failing test along with the ticket. 17 | - If you don't have push access, fork the repository on GitHub. 18 | 19 | Making Changes 20 | -------------- 21 | 22 | - Create a topic branch for your feature or bug fix. 23 | - Make commits of logical units. 24 | - Make sure your commits adhere to the coding guidelines below. 25 | - Make sure your commit messages are in the proper 26 | `Git commit message format`_: 27 | 28 | * The first line of the message should be a 50 characters or less 29 | summary of the change, start with a capital letter and not end with 30 | a period. It is separated by a blank line from the (optional) body. 31 | * The body should be wrapped at 70 characters and paragraphs separated 32 | by blank lines. Bulleted lists are also fine. 33 | * The commit message describes what the changeset introduces and is 34 | written in *present tense* and using the passive form. 35 | - Make sure you have added the necessary tests for your changes. 36 | - Run *all* the tests to assure nothing else was accidentally broken. 37 | 38 | Coding guidelines 39 | ----------------- 40 | 41 | `PEP 0008`_ is enforced, with the exception of `E501`_ and `E226`_: 42 | 43 | * Indent by 4 spaces, tabs are *strictly forbidden*. 44 | * Lines should not exceed 79 characters where possible without severely 45 | impacting legibility. If breaking a line would make the code much 46 | less readable it's fine to overrun by a little bit. 47 | * No trailing whitespace at EOL or trailing blank lines at EOF. 48 | 49 | Checking your commit conforms to coding guidelines 50 | -------------------------------------------------- 51 | 52 | Install a Git pre-commit hook automatically checking for tab and 53 | whitespace errors before committing and also calls ``flake8`` on your 54 | changed files. In the ``.git/hooks`` directory of your local Git 55 | repository, run the following: :: 56 | 57 | git config --local core.whitespace "space-before-tab, tab-in-indent, trailing-space, tabwidth=4" 58 | wget https://gist.github.com/kynan/d233073b66e860c41484/raw/pre-commit 59 | chmod +x pre-commit 60 | 61 | Make sure the ``pre-commit.sample`` hook is still in place, since it is 62 | required. 63 | 64 | Submitting Changes 65 | ------------------ 66 | 67 | - We can only accept your contribution if you have signed the 68 | Contributor License Agreement (CLA). 69 | - Push your changes to a topic branch in your fork of the repository. 70 | - Submit a pull request to the repository in the Taarifa organization. 71 | 72 | .. _GitHub account: https://github.com/signup/free 73 | .. _issues: https://github.com/taarifa/TaarifaAPI/issues 74 | .. _Git commit message format: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html 75 | .. _PEP 0008: http://www.python.org/dev/peps/pep-0008/ 76 | .. _E501: http://pep8.readthedocs.org/en/latest/intro.html#error-codes 77 | .. _E226: http://pep8.readthedocs.org/en/latest/intro.html#error-codes 78 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright 2015 Taarifa Association 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: gunicorn taarifa_api:api 2 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Taarifa API 2 | =========== 3 | 4 | Background 5 | ------------ 6 | 7 | Taarifa_ is an open source platform for the crowd sourced reporting and 8 | triaging of infrastructure related issues. Think of it as a bug tracker for 9 | the real world which helps to engage citizens with their local government. 10 | 11 | Taarifa was founded at the 2011 London WaterHackathon, Winner of the 2013 12 | Sanitation Hackathon, finalist at the 2014 Barcelona World Mobile Congress, 13 | and has been deployed in Uganda, Ghana, and Tanzania. 14 | 15 | 16 | The API 17 | ------- 18 | 19 | The API forms the core of the Taarifa platform. It provides a RESTful 20 | API (built on Flask_ and Eve_) that clients can interact with to create 21 | and triage "bug reports" relating to public infrastructure (e.g., the 22 | public toilet is broken). 23 | 24 | To understand the API it is important to clarify some terminology: 25 | 26 | - **service**: a service provided by some authority (e.g. electricity, 27 | water, road cleaning, ...) 28 | - **facility**: category of physical infrastructure (e.g. power lines, 29 | water pipes, road network, ...) 30 | - **resource**: particular addressable piece of infrastructure (e.g. 31 | Church Street, the waterpoint at (23.44,-5.87)) 32 | - **request**: a ticket/issue/report made by a citizen about a 33 | particular resource, service, or both 34 | 35 | *Aside*: Those familiar with Open311_ will recognize the terminology and 36 | semantics. While the Taarifa API is not fully Open311 compliant yet, 37 | this is on the roadmap. 38 | 39 | Taarifa API provides a way for clients to create services, facilities, 40 | resources, and requests dynamically (at runtime). In particular the 41 | features it provides include: 42 | 43 | - defining new service/facility/resource/request schemas 44 | - automatic validation that submitted service/facility/... instances 45 | conform to the schema 46 | - versioning / history to track changes to resources and requests 47 | 48 | Distributions 49 | ------------- 50 | 51 | The goal is to have different distributions or flavours of Taarifa, built on 52 | top of the core API. The main one is currently the `Taarifa Waterpoints`_ 53 | distribution. 54 | 55 | Installation 56 | ------------ 57 | 58 | Ensure you have installed Python 2.7, pip >= 1.5 and MongoDB 3.0 and that the 59 | MongoDB server `mongod` is running. 60 | 61 | Install virtualenv_ and virtualenvwrapper (you might need admin rights for 62 | this): :: 63 | 64 | pip install virtualenv virtualenvwrapper 65 | 66 | `Set up virtualenvwrapper`_ according to your shell and create a virtualenv: :: 67 | 68 | mkvirtualenv TaarifaAPI 69 | 70 | If you already created the virtualenv, activate it: :: 71 | 72 | workon TaarifaAPI 73 | 74 | Clone the repository: :: 75 | 76 | git clone https://github.com/taarifa/TaarifaAPI 77 | 78 | Change into the directory and install the requirements: :: 79 | 80 | cd TaarifaAPI 81 | pip install -r requirements.txt 82 | 83 | Install the package itself: :: 84 | 85 | python setup.py develop 86 | 87 | 88 | Usage 89 | ----- 90 | 91 | Start the API server from the ``TaarifaAPI`` directory by running: :: 92 | 93 | python taarifa_api/taarifa_api.py 94 | 95 | This starts the API server using a local MongoDB database and requires MongoDB 96 | to be running locally. To use a remote database, export the environment 97 | variable ``MONGOLAB_URI`` with a `connection URI`_ of the form :: 98 | 99 | mongodb://[username:password@]host[:port][/[database]] 100 | 101 | To check things are working, open a browser and navigate to: :: 102 | 103 | http://localhost:5000/api 104 | 105 | This should show you the various endpoints available. To see the API 106 | documentation go to: :: 107 | 108 | http://localhost:5000/docs 109 | 110 | 111 | Contribute 112 | ---------- 113 | 114 | There is still much left do do and Taarifa is currently undergoing rapid 115 | development. To get started send a message to the taarifa-dev_ mailinglist and 116 | check out the github issues. We use the github pull request model for all 117 | contributions. Refer to the `contributing guidelines`_ for further details. 118 | 119 | .. _Taarifa: http://taarifa.org 120 | .. _Taarifa Waterpoints: https://github.com/taarifa/TaarifaWaterpoints 121 | .. _Open311: http://open311.org 122 | .. _taarifa-dev: https://groups.google.com/forum/#!forum/taarifa-dev 123 | .. _Eve: http://python-eve.org 124 | .. _Flask: http://flask.pocoo.org 125 | .. _contributing guidelines: CONTRIBUTING.rst 126 | .. _virtualenv: http://docs.python-guide.org/en/latest/dev/virtualenvs/ 127 | .. _Set up virtualenvwrapper: http://virtualenvwrapper.readthedocs.org/en/latest/install.html#shell-startup-file 128 | .. _connection URI: http://docs.mongodb.org/manual/reference/connection-string/ 129 | -------------------------------------------------------------------------------- /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) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest 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 " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Taarifa.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Taarifa.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/Taarifa" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Taarifa" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Taarifa documentation build configuration file, created by 4 | # sphinx-quickstart on Sat May 24 17:36:26 2014. 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 | 18 | # If extensions (or modules to document with autodoc) are in another directory, 19 | # add these directories to sys.path here. If the directory is relative to the 20 | # documentation root, use os.path.abspath to make it absolute, like shown here. 21 | #sys.path.insert(0, os.path.abspath('.')) 22 | 23 | # -- General configuration ------------------------------------------------ 24 | 25 | # If your documentation needs a minimal Sphinx version, state it here. 26 | #needs_sphinx = '1.0' 27 | 28 | # Add any Sphinx extension module names here, as strings. They can be 29 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 30 | # ones. 31 | extensions = [] 32 | 33 | # Add any paths that contain templates here, relative to this directory. 34 | templates_path = ['_templates'] 35 | 36 | # The suffix of source filenames. 37 | source_suffix = '.rst' 38 | 39 | # The encoding of source files. 40 | #source_encoding = 'utf-8-sig' 41 | 42 | # The master toctree document. 43 | master_doc = 'index' 44 | 45 | # General information about the project. 46 | project = u'Taarifa' 47 | copyright = u'2014, Taarifa Organisation' 48 | 49 | # The version info for the project you're documenting, acts as replacement for 50 | # |version| and |release|, also used in various other places throughout the 51 | # built documents. 52 | # 53 | # The short X.Y version. 54 | version = '1.0' 55 | # The full version, including alpha/beta/rc tags. 56 | release = '1' 57 | 58 | # The language for content autogenerated by Sphinx. Refer to documentation 59 | # for a list of supported languages. 60 | #language = None 61 | 62 | # There are two options for replacing |today|: either, you set today to some 63 | # non-false value, then it is used: 64 | #today = '' 65 | # Else, today_fmt is used as the format for a strftime call. 66 | #today_fmt = '%B %d, %Y' 67 | 68 | # List of patterns, relative to source directory, that match files and 69 | # directories to ignore when looking for source files. 70 | exclude_patterns = ['_build'] 71 | 72 | # The reST default role (used for this markup: `text`) to use for all 73 | # documents. 74 | #default_role = None 75 | 76 | # If true, '()' will be appended to :func: etc. cross-reference text. 77 | #add_function_parentheses = True 78 | 79 | # If true, the current module name will be prepended to all description 80 | # unit titles (such as .. function::). 81 | #add_module_names = True 82 | 83 | # If true, sectionauthor and moduleauthor directives will be shown in the 84 | # output. They are ignored by default. 85 | #show_authors = False 86 | 87 | # The name of the Pygments (syntax highlighting) style to use. 88 | pygments_style = 'sphinx' 89 | 90 | # A list of ignored prefixes for module index sorting. 91 | #modindex_common_prefix = [] 92 | 93 | # If true, keep warnings as "system message" paragraphs in the built documents. 94 | #keep_warnings = False 95 | 96 | 97 | # -- Options for HTML output ---------------------------------------------- 98 | 99 | # The theme to use for HTML and HTML Help pages. See the documentation for 100 | # a list of builtin themes. 101 | html_theme = 'default' 102 | 103 | # Theme options are theme-specific and customize the look and feel of a theme 104 | # further. For a list of options available for each theme, see the 105 | # documentation. 106 | #html_theme_options = {} 107 | 108 | # Add any paths that contain custom themes here, relative to this directory. 109 | #html_theme_path = [] 110 | 111 | # The name for this set of Sphinx documents. If None, it defaults to 112 | # " v documentation". 113 | #html_title = None 114 | 115 | # A shorter title for the navigation bar. Default is the same as html_title. 116 | #html_short_title = None 117 | 118 | # The name of an image file (relative to this directory) to place at the top 119 | # of the sidebar. 120 | #html_logo = None 121 | 122 | # The name of an image file (within the static path) to use as favicon of the 123 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 124 | # pixels large. 125 | #html_favicon = None 126 | 127 | # Add any paths that contain custom static files (such as style sheets) here, 128 | # relative to this directory. They are copied after the builtin static files, 129 | # so a file named "default.css" will overwrite the builtin "default.css". 130 | html_static_path = ['_static'] 131 | 132 | # Add any extra paths that contain custom files (such as robots.txt or 133 | # .htaccess) here, relative to this directory. These files are copied 134 | # directly to the root of the documentation. 135 | #html_extra_path = [] 136 | 137 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 138 | # using the given strftime format. 139 | #html_last_updated_fmt = '%b %d, %Y' 140 | 141 | # If true, SmartyPants will be used to convert quotes and dashes to 142 | # typographically correct entities. 143 | #html_use_smartypants = True 144 | 145 | # Custom sidebar templates, maps document names to template names. 146 | #html_sidebars = {} 147 | 148 | # Additional templates that should be rendered to pages, maps page names to 149 | # template names. 150 | #html_additional_pages = {} 151 | 152 | # If false, no module index is generated. 153 | #html_domain_indices = True 154 | 155 | # If false, no index is generated. 156 | #html_use_index = True 157 | 158 | # If true, the index is split into individual pages for each letter. 159 | #html_split_index = False 160 | 161 | # If true, links to the reST sources are added to the pages. 162 | #html_show_sourcelink = True 163 | 164 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 165 | #html_show_sphinx = True 166 | 167 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 168 | #html_show_copyright = True 169 | 170 | # If true, an OpenSearch description file will be output, and all pages will 171 | # contain a tag referring to it. The value of this option must be the 172 | # base URL from which the finished HTML is served. 173 | #html_use_opensearch = '' 174 | 175 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 176 | #html_file_suffix = None 177 | 178 | # Output file base name for HTML help builder. 179 | htmlhelp_basename = 'Taarifadoc' 180 | 181 | 182 | # -- Options for LaTeX output --------------------------------------------- 183 | 184 | latex_elements = { 185 | # The paper size ('letterpaper' or 'a4paper'). 186 | #'papersize': 'letterpaper', 187 | 188 | # The font size ('10pt', '11pt' or '12pt'). 189 | #'pointsize': '10pt', 190 | 191 | # Additional stuff for the LaTeX preamble. 192 | #'preamble': '', 193 | } 194 | 195 | # Grouping the document tree into LaTeX files. List of tuples 196 | # (source start file, target name, title, 197 | # author, documentclass [howto, manual, or own class]). 198 | latex_documents = [ 199 | ('index', 'Taarifa.tex', u'Taarifa Documentation', 200 | u'Taarifa Organisation', 'manual'), 201 | ] 202 | 203 | # The name of an image file (relative to this directory) to place at the top of 204 | # the title page. 205 | #latex_logo = None 206 | 207 | # For "manual" documents, if this is true, then toplevel headings are parts, 208 | # not chapters. 209 | #latex_use_parts = False 210 | 211 | # If true, show page references after internal links. 212 | #latex_show_pagerefs = False 213 | 214 | # If true, show URL addresses after external links. 215 | #latex_show_urls = False 216 | 217 | # Documents to append as an appendix to all manuals. 218 | #latex_appendices = [] 219 | 220 | # If false, no module index is generated. 221 | #latex_domain_indices = True 222 | 223 | 224 | # -- Options for manual page output --------------------------------------- 225 | 226 | # One entry per manual page. List of tuples 227 | # (source start file, name, description, authors, manual section). 228 | man_pages = [ 229 | ('index', 'taarifa', u'Taarifa Documentation', 230 | [u'Taarifa Organisation'], 1) 231 | ] 232 | 233 | # If true, show URL addresses after external links. 234 | #man_show_urls = False 235 | 236 | 237 | # -- Options for Texinfo output ------------------------------------------- 238 | 239 | # Grouping the document tree into Texinfo files. List of tuples 240 | # (source start file, target name, title, author, 241 | # dir menu entry, description, category) 242 | texinfo_documents = [ 243 | ('index', 'Taarifa', u'Taarifa Documentation', 244 | u'Taarifa Organisation', 'Taarifa', 'One line description of project.', 245 | 'Miscellaneous'), 246 | ] 247 | 248 | # Documents to append as an appendix to all manuals. 249 | #texinfo_appendices = [] 250 | 251 | # If false, no module index is generated. 252 | #texinfo_domain_indices = True 253 | 254 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 255 | #texinfo_show_urls = 'footnote' 256 | 257 | # If true, do not generate a @detailmenu in the "Top" node's menu. 258 | #texinfo_no_detailmenu = False 259 | 260 | 261 | # -- Options for Epub output ---------------------------------------------- 262 | 263 | # Bibliographic Dublin Core info. 264 | epub_title = u'Taarifa' 265 | epub_author = u'Taarifa Organisation' 266 | epub_publisher = u'Taarifa Organisation' 267 | epub_copyright = u'2014, Taarifa Organisation' 268 | 269 | # The basename for the epub file. It defaults to the project name. 270 | #epub_basename = u'Taarifa' 271 | 272 | # The HTML theme for the epub output. Since the default themes are not optimized 273 | # for small screen space, using the same theme for HTML and epub output is 274 | # usually not wise. This defaults to 'epub', a theme designed to save visual 275 | # space. 276 | #epub_theme = 'epub' 277 | 278 | # The language of the text. It defaults to the language option 279 | # or en if the language is not set. 280 | #epub_language = '' 281 | 282 | # The scheme of the identifier. Typical schemes are ISBN or URL. 283 | #epub_scheme = '' 284 | 285 | # The unique identifier of the text. This can be a ISBN number 286 | # or the project homepage. 287 | #epub_identifier = '' 288 | 289 | # A unique identification for the text. 290 | #epub_uid = '' 291 | 292 | # A tuple containing the cover image and cover page html template filenames. 293 | #epub_cover = () 294 | 295 | # A sequence of (type, uri, title) tuples for the guide element of content.opf. 296 | #epub_guide = () 297 | 298 | # HTML files that should be inserted before the pages created by sphinx. 299 | # The format is a list of tuples containing the path and title. 300 | #epub_pre_files = [] 301 | 302 | # HTML files shat should be inserted after the pages created by sphinx. 303 | # The format is a list of tuples containing the path and title. 304 | #epub_post_files = [] 305 | 306 | # A list of files that should not be packed into the epub file. 307 | epub_exclude_files = ['search.html'] 308 | 309 | # The depth of the table of contents in toc.ncx. 310 | #epub_tocdepth = 3 311 | 312 | # Allow duplicate toc entries. 313 | #epub_tocdup = True 314 | 315 | # Choose between 'default' and 'includehidden'. 316 | #epub_tocscope = 'default' 317 | 318 | # Fix unsupported image types using the PIL. 319 | #epub_fix_images = False 320 | 321 | # Scale large images. 322 | #epub_max_image_width = 0 323 | 324 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 325 | #epub_show_urls = 'inline' 326 | 327 | # If false, no index is generated. 328 | #epub_use_index = True 329 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. Taarifa documentation master file, created by 2 | sphinx-quickstart on Sat May 24 17:36:26 2014. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to Taarifa's documentation! 7 | =================================== 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | introduction 15 | 16 | 17 | Indices and tables 18 | ================== 19 | 20 | * :ref:`genindex` 21 | * :ref:`modindex` 22 | * :ref:`search` 23 | -------------------------------------------------------------------------------- /docs/introduction.rst: -------------------------------------------------------------------------------- 1 | ../README.rst -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Taarifa.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Taarifa.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | dnspython==2.6.1 2 | Eve==1.1.2 3 | Eve-Swagger==0.1.1 4 | Flask-Compress==1.3.0 5 | gunicorn==22.0.0 -------------------------------------------------------------------------------- /runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.8.6 2 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup(name='TaarifaAPI', 4 | version='0.2.0', 5 | description='The Taarifa API for managing resources and requests', 6 | long_description=open('README.rst').read(), 7 | author='Florian Rathgeber', 8 | author_email='florian.rathgeber@gmail.com', 9 | license='Apache License, Version 2.0', 10 | url='http://taarifa.org', 11 | download_url='https://github.com/taarifa/TaarifaAPI', 12 | classifiers=[ 13 | 'Development Status :: 3 - Alpha', 14 | 'Intended Audience :: Developers', 15 | 'Intended Audience :: Science/Research', 16 | 'License :: OSI Approved :: Apache Software License', 17 | 'Operating System :: OS Independent', 18 | 'Programming Language :: Python :: 2', 19 | 'Programming Language :: Python :: 2.6', 20 | 'Programming Language :: Python :: 2.7', 21 | ], 22 | packages=['taarifa_api'], 23 | entry_points={"console_scripts": 24 | ["taarifa_api = taarifa_api.taarifa_api:main"]}, 25 | include_package_data=True, 26 | zip_safe=False, 27 | install_requires=['Eve==1.1.2', 28 | 'Eve-Swagger==0.1.1', 29 | 'Flask-Compress==1.3.0']) 30 | -------------------------------------------------------------------------------- /taarifa_api/__init__.py: -------------------------------------------------------------------------------- 1 | from .taarifa_api import api, main, get_schema # noqa 2 | from .taarifa_api import add_document, delete_document, delete_documents, update_document # noqa 3 | -------------------------------------------------------------------------------- /taarifa_api/schemas.py: -------------------------------------------------------------------------------- 1 | boolean_field_false = {'type': 'boolean', 'default': False} 2 | boolean_field_true = {'type': 'boolean', 'default': True} 3 | integer_field = {'type': 'integer'} 4 | float_field = {'type': 'float'} 5 | list_field = {'type': 'list'} 6 | string_field = {'type': 'string'} 7 | unique_string_field = {'type': 'string', 'unique': True} 8 | required_string_field = {'type': 'string', 'required': True} 9 | unique_req_string_field = {'type': 'string', 'required': True, 'unique': True} 10 | dict_field = {'type': 'dict'} 11 | data_relation = {'type': 'dict', 12 | 'schema': {'resource': string_field, 13 | 'field': string_field, 14 | 'embeddable': boolean_field_false, 15 | 'version': boolean_field_false}} 16 | 17 | field_schema = { 18 | 'type': { 19 | 'type': 'string', 20 | 'allowed': ['string', 21 | 'boolean', 22 | 'integer', 23 | 'float', 24 | 'number', 25 | 'datetime', 26 | 'dict', 27 | 'list', 28 | 'objectid', 29 | 'file', 30 | 'point'], 31 | }, 32 | 'required': boolean_field_false, 33 | 'readonly': boolean_field_false, 34 | 'minlength': integer_field, 35 | 'maxlength': integer_field, 36 | 'min': integer_field, 37 | 'max': integer_field, 38 | 'allowed': list_field, 39 | 'empty': boolean_field_true, 40 | 'items': list_field, 41 | 'schema': dict_field, 42 | 'unique': boolean_field_false, 43 | 'data_relation': data_relation, 44 | 'nullable': boolean_field_false, 45 | 'default': {}, 46 | 'versioned': boolean_field_true, 47 | 'label': string_field, 48 | } 49 | 50 | # Service attributes conforming to the Open311 GeoReport v2 service definition: 51 | # http://wiki.open311.org/GeoReport_v2#Response_2 52 | attribute_schema = { 53 | 'variable': boolean_field_true, 54 | 'code': unique_string_field, 55 | 'datatype': { 56 | 'type': 'string', 57 | 'allowed': ['string', 58 | 'number', 59 | 'datetime', 60 | 'text', 61 | 'singlevaluelist', 62 | 'multivaluelist'], 63 | }, 64 | 'required': boolean_field_false, 65 | 'datatype_description': string_field, 66 | 'order': integer_field, 67 | 'description': string_field, 68 | 'values': { 69 | 'type': 'list', 70 | 'schema': { 71 | 'key': string_field, 72 | 'name': string_field, 73 | }, 74 | }, 75 | # This field is not part of the Open311 service definition, but allows to 76 | # enforce foreign key constraints in the API 77 | 'relation': data_relation, 78 | } 79 | 80 | # Service conforming to the Open311 GeoReport v2 service definition: 81 | # http://wiki.open311.org/GeoReport_v2#Response 82 | # endpoint is an extra fields to denote the dynamically created endpoint for 83 | # the service 84 | service_schema = { 85 | 'jurisdiction_id': string_field, 86 | 'service_code': unique_req_string_field, 87 | 'service_name': required_string_field, 88 | 'description': string_field, 89 | 'metadata': boolean_field_false, 90 | 'type': { 91 | 'type': 'string', 92 | 'allowed': ['realtime', 'batch', 'blackbox'], 93 | 'default': 'realtime', 94 | }, 95 | 'keywords': { 96 | 'type': 'list', 97 | 'schema': string_field, 98 | }, 99 | 'group': string_field, 100 | 'attributes': { 101 | 'type': 'list', 102 | 'schema': attribute_schema, 103 | }, 104 | 'endpoint': string_field, 105 | } 106 | 107 | 108 | def attributes2schema(attributes): 109 | """Transform the list of Open311 service attributes into a valid Cerberus 110 | schema (see: http://wiki.open311.org/GeoReport_v2#Response_2).""" 111 | schema = {} 112 | for attr in attributes: 113 | if attr['variable']: 114 | typ = attr['datatype'] 115 | # Attributes of type 'text', 'singlevaluelist', 'multivaluelist' 116 | # are represented as strings 117 | if typ in ['text', 'singlevaluelist', 'multivaluelist']: 118 | typ = 'string' 119 | field = attr['code'] 120 | schema[field] = {'type': typ, 'required': attr['required']} 121 | # If the attribute has a list of values, use their keys as allowed 122 | # values for this attribute 123 | if 'values' in attr: 124 | schema[field]['allowed'] = [v['key'] for v in attr['values']] 125 | # If the attribute has a data relation, enforce the foreign key 126 | # constraint on it 127 | if 'relation' in attr: 128 | schema[field]['data_relation'] = attr['relation'] 129 | return schema 130 | 131 | # Service request conforming to the Open311 GeoReport v2 request definition: 132 | # http://wiki.open311.org/GeoReport_v2#POST_Service_Request 133 | # http://wiki.open311.org/GeoReport_v2#GET_Service_Requests 134 | request_schema = { 135 | 'jurisdiction_id': string_field, 136 | 'service_code': { 137 | 'type': 'string', 138 | 'required': True, 139 | 'data_relation': { 140 | 'resource': 'services', 141 | 'field': 'service_code', 142 | } 143 | }, 144 | 'attribute': { 145 | 'type': 'dict', 146 | 'dynamicschema': { 147 | 'resource': 'services', 148 | 'field': 'service_code', 149 | 'schema': 'attributes', 150 | 'transform': attributes2schema, 151 | }, 152 | }, 153 | # FIXME: at least one of the location fields is required 154 | 'lat': float_field, 155 | 'long': float_field, 156 | 'address_string': string_field, 157 | 'address_id': string_field, 158 | 'zipcode': string_field, 159 | 'email': string_field, 160 | 'device_id': string_field, 161 | 'account_id': string_field, 162 | 'first_name': string_field, 163 | 'last_name': string_field, 164 | 'phone': string_field, 165 | 'description': string_field, 166 | 'media_url': string_field, 167 | 'status': { 168 | 'type': 'string', 169 | 'allowed': ['open', 'closed'], 170 | 'default': 'open', 171 | }, 172 | 'status_notes': string_field, 173 | 'agency_responsible': string_field, 174 | 'service_notice': string_field, 175 | # requested_datetime = _created 176 | # updated_datetime = _updated 177 | 'expected_datetime': { 178 | 'type': 'datetime', 179 | }, 180 | } 181 | 182 | facility_schema = { 183 | 'jurisdiction_id': string_field, 184 | 'facility_code': unique_req_string_field, 185 | 'facility_name': required_string_field, 186 | 'description': string_field, 187 | 'keywords': { 188 | 'type': 'list', 189 | 'schema': string_field, 190 | }, 191 | 'group': string_field, 192 | 'attributes': { 193 | 'type': 'list', 194 | 'schema': attribute_schema, 195 | }, 196 | 'endpoint': string_field, 197 | 'fields': { 198 | 'required': True, 199 | 'type': 'dict', 200 | 'keyschema': field_schema, 201 | }, 202 | } 203 | 204 | resource_schema = { 205 | 'facility_code': { 206 | 'type': 'string', 207 | 'required': True, 208 | 'data_relation': { 209 | 'resource': 'facilities', 210 | 'field': 'facility_code', 211 | } 212 | }, 213 | } 214 | -------------------------------------------------------------------------------- /taarifa_api/settings.py: -------------------------------------------------------------------------------- 1 | """Global API configuration.""" 2 | 3 | from os import environ 4 | 5 | # This module is both imported from and executed. In the former case only 6 | # relative imports are supported, in the latter only absolute. 7 | try: 8 | from schemas import facility_schema, request_schema, resource_schema, \ 9 | service_schema 10 | except ImportError: 11 | from taarifa_api.schemas import facility_schema, request_schema, \ 12 | resource_schema, service_schema 13 | 14 | API_NAME = 'TaarifaAPI' 15 | URL_PREFIX = environ.get('API_URL_PREFIX', 'api') 16 | if 'EVE_DEBUG' in environ: 17 | DEBUG = True 18 | TRAP_HTTP_EXCEPTIONS = True 19 | TRAP_BAD_REQUEST_KEY_ERRORS = True 20 | 21 | if 'MONGO_URI' in environ: 22 | MONGO_URI = environ['MONGO_URI'] 23 | else: 24 | MONGO_DBNAME = environ.get('MONGO_DBNAME', API_NAME) 25 | 26 | # Enable reads (GET), inserts (POST) and DELETE for resources/collections 27 | # (if you omit this line, the API will default to ['GET'] and provide 28 | # read-only access to the endpoint). 29 | RESOURCE_METHODS = ['GET', 'POST', 'DELETE'] 30 | 31 | # Enable reads (GET), edits (PATCH) and deletes of individual items 32 | # (defaults to read-only item access). 33 | ITEM_METHODS = ['GET', 'PUT', 'PATCH', 'DELETE'] 34 | 35 | services = { 36 | "schema": service_schema, 37 | "transparent_schema_rules": True, 38 | } 39 | 40 | requests = { 41 | "schema": request_schema, 42 | "source": "requests", 43 | "key": "service_code", 44 | } 45 | 46 | facilities = { 47 | "item_title": "facility", 48 | "schema": facility_schema, 49 | "transparent_schema_rules": True, 50 | } 51 | 52 | resources = { 53 | "schema": resource_schema, 54 | "source": "resources", 55 | "key": "facility_code", 56 | } 57 | 58 | DOMAIN = { 59 | 'services': services, 60 | 'requests': requests, 61 | 'facilities': facilities, 62 | 'resources': resources, 63 | } 64 | 65 | # Allow requesting up to 100 results per page 66 | PAGINATION_LIMIT = 100 67 | # FIXME: Temporarily allow CORS requests for development purposes 68 | X_DOMAINS = "*" 69 | # Enable Flask-Compress in debug mode 70 | COMPRESS_DEBUG = True 71 | # gzip compression level 72 | COMPRESS_LEVEL = 9 73 | # Enable document version control 74 | VERSIONING = True 75 | # For debugging 76 | # TRAP_HTTP_EXCEPTIONS = True 77 | # TRAP_BAD_REQUEST_KEY_ERRORS = True 78 | -------------------------------------------------------------------------------- /taarifa_api/taarifa_api.py: -------------------------------------------------------------------------------- 1 | from os import environ, path 2 | 3 | from eve import Eve 4 | from eve.io.mongo import Validator 5 | from eve.methods.delete import delete, deleteitem 6 | from eve.methods.post import post_internal 7 | from eve.methods.put import put 8 | 9 | from flask import current_app as app 10 | from flask_compress import Compress 11 | from eve_swagger import get_swagger_blueprint 12 | 13 | from .settings import API_NAME, requests, resources 14 | 15 | 16 | class KeySchemaValidator(Validator): 17 | 18 | def _validate_dynamicschema(self, schema, field, dct): 19 | """Validate the dictionary `dct` against a schema dynamically read from 20 | another document of (potentially) another resource. 21 | 22 | A `dynamicschema` has the following fields: 23 | 24 | * ``resource``: resource to load the schema from 25 | * ``field``: the field name to use in querying the resource (its value 26 | is taken as the same field in the current document) 27 | * ``schema``: the field in the retrieved document holding the schema 28 | * ``transform``: a function to transform the schema (optional)""" 29 | query = {schema['field']: self.document[schema['field']]} 30 | res = app.data.find_one(schema['resource'], None, **query) 31 | if res: 32 | dynamic_schema = res[schema['schema']] 33 | if 'transform' in schema: 34 | dynamic_schema = schema['transform'](dynamic_schema) 35 | self._validate_schema(dynamic_schema, field, dct, None) 36 | else: 37 | self._error(field, "Could not find any %s for query %s" % 38 | (schema['resource'], query)) 39 | 40 | def _validate_keyschema(self, schema, field, dct): 41 | "Validate all keys of dictionary `dct` against schema `schema`." 42 | for key, value in dct.items(): 43 | self._validate_schema(schema, key, value, None) 44 | 45 | def _validate_type_point(self, field, value): 46 | "Validate a GeoJSON Point." 47 | schema = {'type': {'type': 'string', 'choices': ['Point']}, 48 | 'coordinates': {'type': 'list', 49 | 'minlength': 2, 50 | 'maxlength': 2, 51 | 'schema': {'type': 'float'}}} 52 | self._validate_schema(schema, field, value, None) 53 | if not -180.0 <= value['coordinates'][0] <= 180.0: 54 | self._error(field, "Longitude must be in the range -180.0, 180.0") 55 | if not -90.0 <= value['coordinates'][1] <= 90.0: 56 | self._error(field, "Latitude must be in the range -90.0, 90.0") 57 | 58 | settingsfile = path.join(path.abspath(path.dirname(__file__)), 'settings.py') 59 | api = Eve(API_NAME, validator=KeySchemaValidator, settings=settingsfile) 60 | 61 | Compress(api) 62 | 63 | api.register_blueprint(get_swagger_blueprint()) 64 | api.config['SWAGGER_INFO'] = { 65 | 'title': 'Taarifa API', 66 | 'version': '0.2.0', 67 | } 68 | 69 | resource_url = lambda resource: '/' + api.config['URL_PREFIX'] + '/' + resource 70 | 71 | 72 | def get_schema(resource): 73 | "Get the schema for a given resource." 74 | return api.config['DOMAIN'][resource]['schema'] 75 | 76 | 77 | def add_document(resource, document): 78 | "Add a new document to the given resource." 79 | with api.test_request_context(resource_url(resource)): 80 | return post_internal(resource, payl=document, skip_validation=True) 81 | 82 | 83 | def update_document(resource, document): 84 | "Update an existing document at the given resource." 85 | with api.test_request_context(resource_url(resource)): 86 | return put(resource, payl=document) 87 | 88 | 89 | def delete_document(resource, document): 90 | "Delete a given documents of the given resource." 91 | with api.test_request_context(resource_url(resource)): 92 | return deleteitem(resource, document) 93 | 94 | 95 | def delete_documents(resource): 96 | "Delete all documents of the given resource." 97 | with api.test_request_context(resource_url(resource)): 98 | return delete(resource) 99 | 100 | 101 | def register_resource(resource, schema, source, filt): 102 | """Register a new resource with the given schema and filter. This creates 103 | a new endpoint for the resource, whereas documents are stored in the source 104 | collection and a filter is applied. 105 | 106 | .. note:: This method calls Flask's add_url_rule under the hood, which 107 | raises an AssertionError in debugging mode when used after the first 108 | request was served.""" 109 | api.register_resource(resource, {'item_title': resource, 110 | 'schema': schema, 111 | 'datasource': {'source': source, 112 | 'filter': filt}}) 113 | 114 | 115 | def register_resources(resources, conf): 116 | "Add existing resources as API resources." 117 | for res in resources: 118 | if 'endpoint' in res: 119 | schema = conf['schema'] 120 | schema.update(res['fields']) 121 | register_resource(res['endpoint'], schema, conf['source'], 122 | {conf['key']: res[conf['key']]}) 123 | 124 | register_services = lambda d: register_resources(d, requests) 125 | register_facilities = lambda d: register_resources(d, resources) 126 | 127 | 128 | def add_services(): 129 | "Add existing services as API resources." 130 | with api.app_context(): 131 | register_services(api.data.driver.db['services'].find()) 132 | 133 | 134 | def add_facilities(): 135 | "Add existing facilities as API resources." 136 | with api.app_context(): 137 | register_facilities(api.data.driver.db['facilities'].find()) 138 | 139 | # Register hook to add resource for service when inserted into the database 140 | # FIXME: this hook fails in debug mode due an AssertionError raised by Flask 141 | api.on_insert_services += register_services 142 | api.on_insert_facilities += register_facilities 143 | add_services() 144 | add_facilities() 145 | 146 | 147 | def main(): 148 | # Heroku support: bind to PORT if defined, otherwise default to 5000. 149 | if 'PORT' in environ: 150 | port = int(environ.get('PORT')) 151 | host = '0.0.0.0' 152 | else: 153 | port = 5000 154 | host = '127.0.0.1' 155 | api.run(host=host, port=port) 156 | 157 | if __name__ == '__main__': 158 | main() 159 | --------------------------------------------------------------------------------