Simple python library to deal with URI Templates.

Overview

uritemplate

Documentation -- GitHub -- Travis-CI

Simple python library to deal with URI Templates. The API looks like

from uritemplate import URITemplate, expand

# NOTE: URI params must be strings not integers

gist_uri = 'https://api.github.com/users/sigmavirus24/gists{/gist_id}'
t = URITemplate(gist_uri)
print(t.expand(gist_id='123456'))
# => https://api.github.com/users/sigmavirus24/gists/123456

# or
print(expand(gist_uri, gist_id='123456'))

# also
t.expand({'gist_id': '123456'})
print(expand(gist_uri, {'gist_id': '123456'}))

Where it might be useful to have a class

import requests

class GitHubUser(object):
    url = URITemplate('https://api.github.com/user{/login}')
    def __init__(self, name):
        self.api_url = url.expand(login=name)
        response = requests.get(self.api_url)
        if response.status_code == 200:
            self.__dict__.update(response.json())

When the module containing this class is loaded, GitHubUser.url is evaluated and so the template is created once. It's often hard to notice in Python, but object creation can consume a great deal of time and so can the re module which uritemplate relies on. Constructing the object once should reduce the amount of time your code takes to run.

Installing

pip install uritemplate

License

Modified BSD license

Comments
  • Relicense uritemplate.py

    Relicense uritemplate.py

    In order to allow users of uritemplate to continue using a library with the same API under the same license, let's dual-license our tiny project as both Apache 2 and 3-clause BSD.


    In order to do this, we need the consent of the other 4 contributors to this project:

    • [x] Eeo Jun (@eugene-eeo)
    • [x] Daniel Imhoff (@dwieeb)
    • [x] Philippe Ombredanne (@pombredanne)
    • [x] Jeff Potter (@jpotts18)
    • [x] Dennis Kaarsemaker (@seveas)

    If each of you could comment saying "I give my permission to relicense my contributions to uritemplate.py" I can check your name off the list and then merge this and cut a new release.

    Thanks y'all

    opened by sigmavirus24 10
  • "uritemplate.py" conflicts with "uritemplate" package

    There is a package called uritemplate on the PyPI whose name conflicts with this package. Both packages require you to import uritemplate.

    I ran into this issue because our project requires both github3.py (which depends on uritemplate.py) and google-python-api-client (which depends on uritemplate), which led to the following error:

    from uritemplate import URITemplate
    ImportError: cannot import name URITemplate
    

    I'm not sure what the best solution for this would be. Just thought I'd report it for record-keeping and to see if anyone had any workarounds.

    opened by sloria 7
  • repo and pypi confusion

    repo and pypi confusion

    @sigmavirus24, I like this project a lot. I noticed it's used by the Google API module for Python, so I took a look. I had just implemented a very limited version of URI templates for a requests-based project I've been working on. I didn't know anything about this project or the RFC upon which it's based. When my time allows, I'd like to contribute to this project, if you'd welcome my help.

    I have a few questions, though (maybe some of which you'd like help resolving):

    • Which git repo should be used, this GitHub one or the one on Bitbucket? I presume this one should be, since it's the most recently updated and it has the highest version number in the code. (Should the Bitbucket repo be closed or turned into a mirror of this one? Maybe remove the link to Bitbucket from the README, too.)
    • PyPI has two entries for uritemplate packages:
      • uritemplate 3.0.0 - Which appears to be this project.
      • uritemplate.py 3.0.2 - Despite the newer version number in the name, it appears to be older. I downloaded it and found that __init__.py contains a vesion of "2.0.0".
    • What do you think of giving the project another name? "uritemplate" is a too generic. From another Bitbucket repo of the same name, I found it referred to a "uri-templates" project on Google Code. Google Code linked to a GitHub repo named "uritemplates/uritemplate-py", which is maintained by three of the authors of the RFC. However, the README in that repo links to the PyPI package that happens to be... this project! Not to mention that there are similar projects for other programming languages with similar names. Maybe it's time to pick a totally different name and carry on from there. (I hear "Eric" is a nice name. πŸ˜‰)
    • The documentation is confusing. The docs linked from the README appear to be very old. Maybe a better solution would be to set up a documentation site with github.io to consolidate everything around GitHub.
    • The history document shows that the 3.* versions are less recent than 2.0.0. 3.* is also from 2015, but 2.0.0 is from 2016.

    My apologies for dumping a bunch of things in this one message. I hope I don't seem to be complaining. I have a lot of respect for your contributions to flake8 and requests and this project seems to meet an important need, IMHO. I'd really like to contribute, so maybe these are things I could help with in addition to coding.

    opened by sloanlance 6
  • Package uploaded to wrong index

    Package uploaded to wrong index

    There are two separate packages/projects with the name uritemplate, one is "uritemplate", the other is "uritemplate.py". It seems you are an index owner on both

    On 8/20/16, a package from uritemplate.py was uploaded to the other project's index. This project: https://pypi.python.org/pypi/uritemplate.py/2.0.0 Clobbered this project: https://pypi.python.org/pypi/uritemplate/0.6 With this pre-release version: https://pypi.python.org/pypi/uritemplate/2.0.0rc1

    Can you remove the 2.0.0rc1 package from the other project please?

    Thanks,

    opened by leesouza 6
  • Version 4.1.0 is incompatible with Python 2

    Version 4.1.0 is incompatible with Python 2

    In setup.cfg you are claiming that the newest version should work on Python 2 which is not true. Currently pip in Python 2 allows installing 4.1.0. Noticed this in our CI pipelines as we're installing django-rest-swagger==2.1.2 which has uritemplate (any version) as dependency.

    >>> from uritemplate.api import (URITemplate, expand, partial, variables)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/Users/julius/.virtualenvs/pcloud/lib/python2.7/site-packages/uritemplate/__init__.py", line 28, in <module>
        from uritemplate.api import (
      File "/Users/julius/.virtualenvs/pcloud/lib/python2.7/site-packages/uritemplate/api.py", line 19
        uri: str,
           ^
    SyntaxError: invalid syntax
    
    opened by julius88 5
  • New release?

    New release?

    Looks like there have been a few changes since the last release (in 2013 😳) particularly from last year. Is it worthwhile to cut a new release to get those out? πŸ˜‰

    opened by jakirkham 5
  • [BUG] Non-string var values aren't truly supported

    [BUG] Non-string var values aren't truly supported

    I saw #17 that claimed that int/float vals should be supported and #20 that fixed it back in 2015. Imagine my surprise when I see that removed check in the traceback on passing int.

    Looks like there's a similar place in code that hasn't been fixed for some reason and still causes trouble: https://github.com/python-hyper/uritemplate/blob/3.0.1/uritemplate/variable.py#L194

    $ ipython
    Python 3.7.1 (default, Jan 28 2019, 08:25:13) 
    Type 'copyright', 'credits' or 'license' for more information
    IPython 7.1.1 -- An enhanced Interactive Python. Type '?' for help.
    
    In [1]: import uritemplate                                                         
    
    In [2]: uritemplate.URITemplate('/test{/num}').expand({'num': 3})                  
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-3-5afe50171000> in <module>
    ----> 1 uritemplate.URITemplate('/test{/num}').expand({'num': 3})
    
    ~/.pyenv/versions/3.7.1/lib/python3.7/site-packages/uritemplate/template.py in expand(self, var_dict, **kwargs)
        130 
        131         """
    --> 132         return self._expand(_merge(var_dict, kwargs), False)
        133 
        134     def partial(self, var_dict=None, **kwargs):
    
    ~/.pyenv/versions/3.7.1/lib/python3.7/site-packages/uritemplate/template.py in _expand(self, var_dict, replace)
         95         expanded = {}
         96         for v in self.variables:
    ---> 97             expanded.update(v.expand(expansion))
         98 
         99         def replace_all(match):
    
    ~/.pyenv/versions/3.7.1/lib/python3.7/site-packages/uritemplate/variable.py in expand(self, var_dict)
        336                 expansion = self._string_expansion
        337 
    --> 338             expanded = expansion(name, value, opts['explode'], opts['prefix'])
        339 
        340             if expanded is not None:
    
    ~/.pyenv/versions/3.7.1/lib/python3.7/site-packages/uritemplate/variable.py in _label_path_expansion(self, name, value, explode, prefix)
        188         safe = self.safe
        189 
    --> 190         if value is None or (len(value) == 0 and value != ''):
        191             return None
        192 
    
    TypeError: object of type 'int' has no len()
    
    
    opened by webknjaz 3
  • Make it compatible with Python 3.7+

    Make it compatible with Python 3.7+

    We observed the following deprecation warning in Python 3.7.1+:

    Travis CI log PR: https://github.com/python/bedevere/pull/154 Issue: https://github.com/python/bedevere/issues/153

    ../../../virtualenv/python3.8-dev/lib/python3.8/site-packages/uritemplate/variable.py:363: in dict_test
        return isinstance(value, (dict, collections.MutableMapping))
    
    DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
    

    In this PR I updated the import to avoid the DeprecationWarning and add Python 3.7 to travis CI matrix.

    Thanks for this useful library!

    opened by Mariatta 3
  • Resolve DeprecatioWarning for import of ABCs from 'collections' instead of 'collections.abc'

    Resolve DeprecatioWarning for import of ABCs from 'collections' instead of 'collections.abc'

    Seeing this deprecation warning when running a test suite that depends on uritemplate:

      /home/myusername/venv/lib64/python3.7/site-packages/uritemplate/variable.py:363: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3,and in 3.9 it will stop working
        return isinstance(value, (dict, collections.MutableMapping))
    
    opened by kdelee 2
  • Import ABCs from collections.abc if possible

    Import ABCs from collections.abc if possible

    Using collections.MutableSet and collections.MutableMapping produces a DeprecationWarning under Python 3.7 with the message:

    Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working

    This patch eliminates this warning by importing the ABCs from collections.abc, falling back to collections only if that fails (i.e., if running under Python < 3.3).

    opened by jwodder 2
  • Make variable ordering deterministic

    Make variable ordering deterministic

    We encountered an issue within uritemplate indirectly while using django-rest-framework, which uses it for processing path variables - We occasionally hit problems with the variables being a different order from expected, which seems to be due to the use of the non-deterministic set internally.

    This PR introduces the use OrderedSet , which for the purposes here is using an inline version of it obtained from the ActiveState code snippets. The reason for this is to not introduce a thirdparty dependency into the project, but if that's preferable we can replace it with one such as orderedset (which is based on the same recipe, but implemented in CPython instead).

    Tests have been checked via tox and it works on Py 2+3. Thoughts? :-)

    opened by lskillen 2
  • Incorrect Reserved Expansion

    Incorrect Reserved Expansion

    Valid UTF-8-percent-encoded code points must be preserved in reserved expansion. This implementation (Version: 4.1.1) fails the following test from https://github.com/uri-templates/uritemplate-test/blob/master/extended-tests.json:

    {
      ...
      "Additional Examples 6: Reserved Expansion": {
        "variables" : {
          "id" : "admin%2F",
          ...
      },
      "testcases": [
        ["{+id}", "admin%2F"],
        ...
      ]
    }
    

    The correct/expected expansion is 'admin%2F', the actual expansion is 'admin%252F':

    >>> from uritemplate import URITemplate, expand
    >>> URITemplate('{+id}').expand(id='admin%2F')
    'admin%252F'
    >>> expand('{+id}', id='admin%2F')
    'admin%252F'
    
    opened by watuwo 0
  • Default values

    Default values

    I noticed the implementation allows specifying default values in the template, which is cool, but is not supported by the RFC.

    Maybe this feature should be added to the RFC?

    opened by plinss 5
  • Variable names are not validated

    Variable names are not validated

    The RFC limits the characters allowed in variables names, but there is no validation enforcing this.

    From Β§ 2.3:

     variable-list =  varspec *( "," varspec )
     varspec       =  varname [ modifier-level4 ]
     varname       =  varchar *( ["."] varchar )
     varchar       =  ALPHA / DIGIT / "_" / pct-encoded
    

    (I'm not opposed to expanding the set of allowed characters.)

    opened by plinss 0
  • Potential bug/Unspecified behaviour

    Potential bug/Unspecified behaviour

    Let's look at a template like this:

    http://example.com/dictionary/{term:1}
    

    We have two different behaviours depending upon the value used to expand term.

    >>> import uritemplate
    >>> u = uritemplate.URITemplate('http://example.com/dictionary/{term:1}')
    >>> u.expand(term='foo')
    'http://example.com/dictionary/f'
    >>> u.expand(term=['foo', 'bar', 'bogus'])
    'http://example.com/dictionary/foo,bar,bogus'
    

    A simplified version of this is simply

    {term:1}
    

    In other words:

    >>> import uritemplate
    >>> u = uritemplate.URITemplate('{term:1}')
    >>> u.expand(term='foo')
    'f'
    >>> u.expand(term=['foo', 'bar', 'bogus'])
    'foo,bar,bogus'
    

    All versions of uritemplate (and uritemplate.py) exhibit this behaviour and the RFC does not provide clear guidance.

    I have not investigated how other implementations in other languages handle this, though. There do not appear to be any examples in the RFC that combine lists with length limitations.

    opened by sigmavirus24 4
  • Provide an API for validating URI Templates

    Provide an API for validating URI Templates

    Hi!

    Would you consider an API to validate whether a particular input was valid under RFC 6570 (or does such a thing exist already and I've missed it)?

    E.g., http://example.com/dictionary/{term:1}/{term is not a valid URI Template seemingly, but I cannot see an API that complains about that -- uritemplate.URITemplate will happily truncate the end part there and consider that a template with just one field.

    (Even having URITemplate do enough validation of its inputs would also work).

    Full context: JSON Schema Draft 6 adds a uri-template format. I'd love to use uritemplate to implement it in jsonschema.

    opened by Julian 9
C++ library for urlencode.

liburlencode C library for urlencode.

Khaidi Chu 6 Oct 31, 2022
A simple, immutable URL class with a clean API for interrogation and manipulation.

purl - A simple Python URL class A simple, immutable URL class with a clean API for interrogation and manipulation. Supports Pythons 2.7, 3.3, 3.4, 3.

David Winterbottom 286 Jan 2, 2023
A simple URL shortener built with Flask

A simple URL shortener built with Flask and MongoDB.

Mike Lowe 2 Feb 5, 2022
Simple Version of ouo.io. shorten any link on the web easily

OUO.IO LINK SHORTENER This is a simple python script that made to short links. currently ouo.io doesn't have Application Programming Interface so i de

Danushka-Madushan 1 Dec 11, 2021
Ukiyo - A simple, minimalist and efficient discord vanity URL sniper

Ukiyo - a simple, minimalist and efficient discord vanity URL sniper. Ukiyo is easy to use, has a very visually pleasing interface, and has great spee

null 13 Apr 14, 2022
:electric_plug: Generating short urls with python has never been easier

pyshorteners A simple URL shortening API wrapper Python library. Installing pip install pyshorteners Documentation https://pyshorteners.readthedocs.i

Ellison 350 Dec 24, 2022
encurtador de links feito com python

curt-link encurtador de links feito com python! instalação Linux: $ git clone https://github.com/bydeathlxncer/curt-link $ cd curt-link $ python3 url.

bydeathlxncer 5 Dec 29, 2021
python3 flask based python-url-shortener microservice.

python-url-shortener This repository is for managing all public/private entity specific api endpoints for an organisation. In this case we have entity

Asutosh Parida 1 Oct 18, 2021
A python code for url redirect check

A python code for url redirect check

Fayas Noushad 1 Oct 24, 2021
A url redirect status check module for python

A url redirect status check module for python

Fayas Noushad 2 Oct 24, 2021
Qysqa - URL shortener website with python

Qysqa - shorten your URL. ~ A simple URL-shortening website. how do you pronounc

Dastan Ozgeldi 0 Nov 18, 2022
A tool to manage the base URL of the Python package index.

chpip A tool to manage the base URL of the Python package index. Installation $ pip install chpip Usage Set pip index URL Set the base URL of the Pyth

Prodesire 4 Dec 20, 2022
πŸ”— FusiShort is a URL shortener built with Python, Redis, Docker and Kubernetes

This is a playground application created with goal of applying full cycle software development using popular technologies like Python, Redis, Docker and Kubernetes.

Lucas Fusinato Zanis 7 Nov 10, 2022
Deal or No Deal? End-to-End Learning for Negotiation Dialogues

Introduction This is a PyTorch implementation of the following research papers: (1) Hierarchical Text Generation and Planning for Strategic Dialogue (

Facebook Research 1.4k Dec 29, 2022
Deal Or No Deal was a very popular game show. Even now, for a family party, it's a fun game to pass time

Deal Or No Deal was a very popular game show. Even now, for a family party, it's a fun game to pass time. I made a code to play the game right in your terminal/console. This isn't made to be a game which can be installed by everyone and played, I just made it as a fun project as I just started out with python. So if you have python installed and wanna have some fun, or just curious to see how I did this, feel free to check the code out!

null 1 Feb 15, 2022
Fully Automated YouTube Channel ▢️with Added Extra Features.

Fully Automated Youtube Channel β–’β–ˆβ–€β–€β–ˆ β–ˆβ–€β–€β–ˆ β–€β–€β–ˆβ–€β–€ β–€β–€β–ˆβ–€β–€ β–ˆβ–‘β–‘β–ˆ β–ˆβ–€β–€β–„ β–ˆβ–€β–€ β–ˆβ–€β–€β–ˆ β–’β–ˆβ–€β–€β–„ β–ˆβ–‘β–‘β–ˆ β–‘β–‘β–ˆβ–‘β–‘ β–‘β–’β–ˆβ–‘β–‘ β–ˆβ–‘β–‘β–ˆ β–ˆβ–€β–€β–„ β–ˆβ–€β–€ β–ˆβ–„β–„β–€ β–’β–ˆβ–„β–„β–ˆ β–€β–€β–€β–€ β–‘β–‘β–€β–‘β–‘ β–‘β–’β–ˆβ–‘β–‘ β–‘β–€β–€β–€ β–€β–€β–€β–‘

sam-sepiol 249 Jan 2, 2023
Download all your URI Online Judge source codes and upload to GitHub with simple steps.

URI-Code-Downloader Download all your URI Online Judge source codes and upload to GitHub with simple steps. Prerequisites Python 3.x Installing Downlo

Luan SimΓ΅es 9 Mar 23, 2022
Blender Game Engine Game Type Templates Logic Bricks (and Python script) based Game Templates for Blender

Blender-Game-Engine-Templates Blender Game Engine Game Type Templates Logic Bric

null 3 Oct 25, 2022
Saptak Bhoumik 14 May 24, 2022
A small utility to deal with malware embedded hashes.

Uchihash is a small utility that can save malware analysts the time of dealing with embedded hash values used for various things such as: Dyn

Abdallah Elshinbary 48 Dec 19, 2022