Пример #1
0
def smsc_delivery_image(om_database, smsc_database, om_image, om_server,
                        om_server_port, request):
    """Start the delivery image with a SS7 link and a SMPP link"""
    smppLink = tortilla.wrap('http://{}:{}/v1/deliverySMPPLink'.format(
        om_server, om_server_port),
                             format='json')
    ss7Link = tortilla.wrap('http://{}:{}/v1/deliverySS7Link'.format(
        om_server, om_server_port),
                            format='json')

    smppLink("smppClientLink").put(
        data={
            "connectionType": "client",
            "hostname": "localhost",
            "port": 8888,
            "systemId": "inserter-test",
            "systemType": "systemType",
            "password": "******"
        })
    ss7Link("ss7ClientLink").put(data={
        "hostname": "localhost",
        "port": 9999,
        "token": "test"
    })
    proc = launch_image(
        request, "delivery",
        ["--smscdb-name=" + smsc_database, "--omdb-name=" + om_database])
Пример #2
0
    def __init__(self, url, connection_parameters):
        '''Class constructor'''
        global TORTILLADEBUG
        self.connection_parameters = connection_parameters  # Uggly hack
        self.url = url
        # Tortilla uses a bit of magic to wrap APIs. Whenever you get or call an attribute of a wrapper, the URL is appended by that attribute's name or method parameter.
        self.api_url = tortilla.wrap(url, debug=config.TORTILLADEBUG)

        # logging.getLogger("urllib3").setLevel(logging.WARNING)
        # logging.getLogger("requests").setLevel(logging.WARNING)
        config.logger.debug(
            "------------------------------------------------------------")
        config.logger.debug("Url: %s" % url)
        config.logger.debug("Header: %s" % connection_parameters.headers)
        config.logger.debug(
            "------------------------------------------------------------")

        # trying to do a GET request with the current url
        try:
            self.data = self.api_url.get(
                verify=connection_parameters.verify_cert,
                headers=connection_parameters.headers)
        except (requests.ConnectionError, ssl.SSLError) as e:
            # Log and transmit the exception.
            config.logger.info('Raise a RedfishException to upper level')
            msg = 'Connection error : {}\n'.format(e)
            raise exception.ConnectionFailureException(msg)
        except simplejson.scanner.JSONDecodeError as e:
            # Log and transmit the exception.
            config.logger.info('Raise a RedfishException to upper level')
            msg = \
                'Ivalid content : Content does not appear to be a valid ' + \
                'Redfish json\n'
            raise exception.InvalidRedfishContentException(msg)
        config.logger.debug(pprint.PrettyPrinter(indent=4).pformat(self.data))
Пример #3
0
    def __init__(self, url, connection_parameters):
        '''Class constructor'''
        global TORTILLADEBUG
        self.connection_parameters = connection_parameters  # Uggly hack
        self.url = url
        self.api_url = tortilla.wrap(url, debug=config.TORTILLADEBUG)

        config.logger.debug(
            "------------------------------------------------------------")
        config.logger.debug("Url: %s" % url)
        config.logger.debug("Header: %s" % connection_parameters.headers)
        config.logger.debug(
            "------------------------------------------------------------")

        try:
            self.data = self.api_url.get(
                verify=connection_parameters.verify_cert,
                headers=connection_parameters.headers)
        except (requests.ConnectionError, ssl.SSLError) as e:
            # Log and transmit the exception.
            config.logger.info('Raise a RedfishException to upper level')
            msg = 'Connection error : {}\n'.format(e)
            raise exception.ConnectionFailureException(msg)
        except simplejson.scanner.JSONDecodeError as e:
            # Log and transmit the exception.
            config.logger.info('Raise a RedfishException to upper level')
            msg = \
                'Ivalid content : Content does not appear to be a valid ' + \
                'Redfish json\n'
            raise exception.InvalidRedfishContentException(msg)
        config.logger.debug(pprint.PrettyPrinter(indent=4).pformat(self.data))
Пример #4
0
 def __init__(self, key=None, host="https://api.citiesense.com", **kwargs):
     if key is None:
         raise APIKeyMissingError("All methods require an API key.")
     kwargs.update({'extension': 'json'})
     api = tortilla.wrap(host, **kwargs)
     api.config.headers["X-Api-Key"] = key
     self.api = api
Пример #5
0
def cli(host, token, debug, command):

    with open('grid.json') as gridjson:
        json_dict = json.loads(gridjson.read())
        grid = tortilla.wrap(json_dict['host'])
        grid.config.headers.token = json_dict['token']


    while True:
        try:
            val = grid_prompt()
            if val:
                if val == 'exit' or val == 'quit':
                    break
                print(command_parser(grid, *val.split()))
        except KeyboardInterrupt:
            break
        except EOFError:
            break
        except Exception as e:
            if debug:
                raise e
            else:
                print('ERROR:', e)
    print('Bye!')
Пример #6
0
def eject_virtual_media():
    global TORTILLADEBUG
    redpool = redfish.main.connect("https://10.1.213.135/redfish/v1",
                                   "admin",
                                   "admin",
                                   simulator=False,
                                   verify_cert=False)
    for key, value in redpool.Managers.managers_dict.iteritems():
        url = value.get_link_url('VirtualMedia')
        # print url
        cp = redpool.connection_parameters
        vm_list = redfish.types.BaseCollection(url, cp)
        for item in vm_list.get_parameter("Members"):
            for idx, value in item.iteritems():
                url2 = urljoin(url, value)
                vm = redfish.types.Base(url2, cp)
                if "CD" in vm.get_parameter("MediaTypes"):
                    url2 = vm.get_parameters()["Oem"]["Hpe"]["Actions"][
                        "#HpeiLOVirtualMedia.EjectVirtualMedia"]["target"]
                    url2 = urljoin(url, url2)
                    body = dict()

                    api_url = tortilla.wrap(url2, debug=True)
                    response = api_url.post(
                        verify=vm.connection_parameters.verify_cert,
                        headers=vm.connection_parameters.headers,
                        data=body)
                    print(response)
    redpool.logout()
    return
Пример #7
0
class AcousticBrainz:

    url = 'https://acousticbrainz.org/api/v1'

    # Create Tortilla object:
    acousticbrainz = tortilla.wrap(url)

    def get_track_data(self,
                       mbid,
                       level,
                       submission_number=None,
                       waiting_for=0.25):
        if submission_number:
            sleep(waiting_for)
            return self.acousticbrainz(mbid)(level).get(
                params={'n': submission_number})
        else:
            sleep(waiting_for)
            return self.acousticbrainz(mbid).get(level)

    def get_number_of_submissions(self, mbid, waiting_for=0.25):
        """
        Number of submissions = How many times data for the same track were
        POSTed to the AcousticBrainz database.
        """
        sleep(waiting_for)
        return self.acousticbrainz(mbid).count.get()
Пример #8
0
    def __init__(self, url, connection_parameters):
        '''Class constructor'''
        global TORTILLADEBUG
        self.connection_parameters = connection_parameters  # Uggly hack
        self.url = url
        self.api_url = tortilla.wrap(url, debug=config.TORTILLADEBUG)

        config.logger.debug(
            "------------------------------------------------------------")
        config.logger.debug("Url: %s" % url)
        config.logger.debug("Header: %s" % connection_parameters.headers)
        config.logger.debug(
            "------------------------------------------------------------")

        try:
            self.data = self.api_url.get(
                verify=connection_parameters.verify_cert,
                headers=connection_parameters.headers)
        except (requests.ConnectionError, ssl.SSLError) as e:
            # Log and transmit the exception.
            config.logger.info('Raise a RedfishException to upper level')
            msg = 'Connection error : {}\n'.format(e)
            raise exception.ConnectionFailureException(msg)
        except simplejson.scanner.JSONDecodeError as e:
            # Log and transmit the exception.
            config.logger.info('Raise a RedfishException to upper level')
            msg = \
                'Ivalid content : Content does not appear to be a valid ' + \
                'Redfish json\n'
            raise exception.InvalidRedfishContentException(msg)
        config.logger.debug(pprint.PrettyPrinter(indent=4).pformat(self.data))
Пример #9
0
    def __init__(self,
                 email='',
                 password='',
                 refresh_deadline_sec=30,
                 tortilla_debug=False,
                 tortilla_cache: Type[BaseCache] = DictCache(),
                 tortilla_cache_lifetime: Optional[int] = None) -> None:
        self.root = wrap(self.ENDPOINT,
                         cache=tortilla_cache,
                         cache_lifetime=tortilla_cache_lifetime,
                         debug=tortilla_debug)
        self.refresh_deadline_sec = refresh_deadline_sec
        self.access_token = ''
        self.refresh_token = ''
        self.me = Bunch()
        self.expires_at: Optional[datetime] = None

        self.auth = Auth(self)
        self.tag = Tag(self)
        self.doujinshi = Doujinshi(self)
        self.changelog = Changelog(self)
        self.user = User(self)
        self.library = Library(self)
        self.following = Following(self)
        self.notifications = Notifications(self)

        if email and password:
            self.auth.login(email, password)
Пример #10
0
 def test_formed_urls(self):
     assert api.this.url() == API_URL + '/this'
     assert api('this').url() == API_URL + '/this'
     assert api.this('that').url() == API_URL + '/this/that'
     assert api('this')('that').url() == API_URL + '/this/that'
     assert api.user('имя').url() == API_URL + '/user/имя'
     trailing_slash_api = tortilla.wrap(API_URL + '/')
     assert trailing_slash_api.endpoint.url() == API_URL + '/endpoint'
Пример #11
0
    def __init__(self, host, username, password):
        self.host = host
        self.username = username
        self.password = password

        self.api = tortilla.wrap(self.host,
                                 auth=HTTPBasicAuth(self.username,
                                                    self.password))
Пример #12
0
def smsc_delivery_image(om_database, smsc_database, om_image, om_server, om_server_port, request):
    """Start the delivery image with a SS7 link and a SMPP link"""
    smppLink = tortilla.wrap('http://{}:{}/v1/deliverySMPPLink'.format(om_server, om_server_port), format='json')
    ss7Link = tortilla.wrap('http://{}:{}/v1/deliverySS7Link'.format(om_server, om_server_port), format='json')

    smppLink("smppClientLink").put(data={
                                        "connectionType" : "client",
                                        "hostname": "localhost",
                                        "port": 8888,
                                        "systemId": "inserter-test",
                                        "systemType": "systemType",
                                        "password": "******"})
    ss7Link("ss7ClientLink").put(data={
                                        "hostname": "localhost",
                                        "port": 9999,
                                        "token": "test"})
    proc = launch_image(request, "delivery", ["--smscdb-name=" + smsc_database, "--omdb-name=" + om_database])
Пример #13
0
def get_asistentes(pagina, evento):
    """
    Obtener asistenes de un evento usando la API de meetup.

    Más información en la documentación oficial de meetup:
    https://www.meetup.com/es/meetup_api/docs/:urlname/events/:id/attendance/
    """
    api = tortilla.wrap(f"https://api.meetup.com/{pagina}")
    return api.events(evento).attendance.get()
Пример #14
0
 def test_formed_urls(self):
     assert api.this.url() == API_URL + '/this'
     assert api('this').url() == API_URL + '/this'
     assert api.this('that').url() == API_URL + '/this/that'
     assert api('this')('that').url() == API_URL + '/this/that'
     assert api.user('имя').url() == API_URL + '/user/имя'
     trailing_slash_api = tortilla.wrap(API_URL + '/')
     assert trailing_slash_api.endpoint.url() == API_URL + '/endpoint'
     assert api('hello', 'world').url() == API_URL + '/hello/world'
     assert api('products', 123).url() == API_URL + '/products/123'
Пример #15
0
 def test_formed_urls(self):
     assert api.this.url() == API_URL + '/this'
     assert api('this').url() == API_URL + '/this'
     assert api.this('that').url() == API_URL + '/this/that'
     assert api('this')('that').url() == API_URL + '/this/that'
     assert api.user('имя').url() == API_URL + '/user/имя'
     trailing_slash_api = tortilla.wrap(API_URL + '/')
     assert trailing_slash_api.endpoint.url() == API_URL + '/endpoint'
     assert api('hello', 'world').url() == API_URL + '/hello/world'
     assert api('products', 123).url() == API_URL + '/products/123'
Пример #16
0
def Question():
    # Wrap the jService API
    jService = tortilla.wrap('http://jservice.io/api')
    # Fetch a random trivia question from the jService.io API
    try:
        response = jService.random.get(params={'count': 1})[0]
    except Exception as e:
        return False
    # Retreive only the question from the response object
    question = response['question']
    return question
Пример #17
0
    def __init__(self, url, username=None, password=None, delay=0.,
                 debug=False):
        super(Camomile, self).__init__()

        # internally rely on tortilla generic API wrapper
        # see http://github.com/redodo/tortilla
        self._api = tortilla.wrap(url, format='json', delay=delay, debug=debug)

        # log in if `username` is provided
        if username:
            self.login(username, password)
Пример #18
0
def BingBackground():
    # Wrap the Bing HPImageArchive API
    HPImageArchive = tortilla.wrap('http://www.bing.com/HPImageArchive.aspx')
    response = HPImageArchive.get(params={
        'format': 'js',
        'idx': 0,
        'n': 1,
        'mkt': 'en-US'
    })
    image = 'http://bing.com/%s' % response['images'][0]['url']
    return image
def test_inserter(host, port):
    inserter_collection_api = tortilla.wrap('http://{}:{}/v1/inserterSMPPLinks'.format(host, port), format='json')
    inserter_api = tortilla.wrap('http://{}:{}/v1/inserterSMPPLink'.format(host, port), format='json')
    inserter_api.config.headers = {'Content-Type': 'application/json'}

    client={"connectionType": "client",
          "hostname": "127.0.0.1",
          "port": 88,
          "systemId": "systemId",
          "systemType": "systemType",
          "password": "******"}
    server={"connectionType": "server",
          "port": 99,
          "systemId": "systemId",
          "systemType": "systemType",
          "password": "******",
          "allowedRemoteAddress": "127.0.0.1",
          "allowedRemotePort": 99}

    inserter_api("client").put(data=client)
    inserter_api("client").get()
    inserter_api("server").put(data=server)
    inserter_api("server").get()
    inserter_collection_api.get()

    # test update
    client['port'] = 99
    inserter_api("client").put(data=client)
    client_answer = inserter_api("client").get()
    if not client_answer['port'] == 99:
        sys.exit(1)

    server['allowedRemotePort'] = 101
    inserter_api("server").put(data=server)
    server_answer = inserter_api("server").get()
    if not server_answer['allowedRemotePort'] == 101:
        sys.exit(1)

    inserter_api("client").delete()
    inserter_api("server").delete()
Пример #20
0
    def __init__(self,
                 url,
                 username=None,
                 password=None,
                 delay=0.,
                 debug=False):
        super(Camomile, self).__init__()

        # internally rely on tortilla generic API wrapper
        # see http://github.com/redodo/tortilla
        self._api = tortilla.wrap(url, format='json', delay=delay, debug=debug)

        # log in if `username` is provided
        if username:
            self.login(username, password)
Пример #21
0
    def __tortilla_api(self):
        url = self.get_url()
        if 'api_key' in self.__dict__ and self.api_key:
            self.headers.update({'apikey': self.api_key})
        if 'user' in self.__dict__ and \
            'password' in self.__dict__ and \
            self.user and self.password:
            self.headers.update(
                {'Authorization': _basic_auth_str(self.user, self.password)})
        else:
            pass

        args = {}
        for a in self.tortilla_defaults.keys():
            args[a] = self.__dict__[a]
        return tortilla.wrap(url, **args)
Пример #22
0
    def __init__(self, es_url,
                 es_index, es_doctype,
                 es_batchsize=0, es_delete=False,
                 log_level='info'
    ):
        DataStorer.__init__(self)

        self.log_level = log_level
        self.es_url = es_url
        self.es_index = es_index
        self.es_doctype = es_doctype
        self.es_batchsize = es_batchsize
        self.es_delete = es_delete

        self.logger.setLevel(getattr(logging, self.log_level.upper(), logging.WARNING))

        self.est = tortilla.wrap(self.es_url)

        self.es_setup()
Пример #23
0
    def __tortilla_api(self):
        url = self.get_url()
        if 'api_key' in self.__dict__ and self.api_key:
            self.headers.update({'apikey': self.api_key})
        if 'user' in self.__dict__ and \
            'password' in self.__dict__ and \
            self.user and self.password:
            self.headers.update({
                'Authorization': _basic_auth_str(
                    self.user, self.password
                )
            })
        else:
            pass

        args = {}
        for a in self.tortilla_defaults.keys():
            args[a] = self.__dict__[a]
        return tortilla.wrap(url, **args)
Пример #24
0
    def __init__(self, url, connection_parameters):
        """Class constructor"""
        global TORTILLADEBUG
        self.connection_parameters = connection_parameters # Uggly hack to check
        self.url = url
        self.api_url = tortilla.wrap(url, debug=config.TORTILLADEBUG)

        try:
            if connection_parameters.auth_token == None:
                self.data = self.api_url.get(verify=connection_parameters.verify_cert)
            else:
                self.data = self.api_url.get(verify=connection_parameters.verify_cert,
                                             headers={'x-auth-token': connection_parameters.auth_token}
                                             )
        except requests.ConnectionError as e:
            print e
            # Log and transmit the exception.
            config.logger.error("Connection error : %s", e)
            raise e
        print self.data
Пример #25
0
    def __init__(self,
                 es_url,
                 es_index,
                 es_doctype,
                 es_batchsize=0,
                 es_delete=False,
                 log_level='info'):
        DataStorer.__init__(self)

        self.log_level = log_level
        self.es_url = es_url
        self.es_index = es_index
        self.es_doctype = es_doctype
        self.es_batchsize = es_batchsize
        self.es_delete = es_delete

        self.logger.setLevel(
            getattr(logging, self.log_level.upper(), logging.WARNING))

        self.est = tortilla.wrap(self.es_url)

        self.es_setup()
Пример #26
0
def change_power_status(value=None):
    redpool = redfish.main.connect("https://10.1.213.135/redfish/v1",
                                   "admin",
                                   "admin",
                                   simulator=False,
                                   verify_cert=False)
    for key, value in redpool.Systems.systems_dict.iteritems():
        print("Curret Power Status is:")
        print(value.get_parameter('PowerState'))
        options = value.get_parameters()["Actions"]['#ComputerSystem.Reset'][
            '*****@*****.**']
        print(
            "You have following option in which you can change the Power Status"
        )
        print(options)
        print("Enter the Value to which you want to change Power Status to:")
        res = raw_input()
        if res not in options:
            print("You have entered a invalid input, aborting this process!!")
            return
        target = value.get_parameters(
        )["Actions"]['#ComputerSystem.Reset']["target"]
        url = urljoin(value.url, target)
        action = dict()
        # action['Action'	] = 'Reset'
        action['ResetType'] = res
        api_url = tortilla.wrap(url, debug=True)

        response = api_url.post(verify=value.connection_parameters.verify_cert,
                                headers=value.connection_parameters.headers,
                                data=action)
        # response = value.api_url.post(
        #           verify=value.connection_parameters.verify_cert,
        #           headers=value.connection_parameters.headers,
        #           data=action)

        print(response)

    redpool.logout()
Пример #27
0
def dashboard(request, username):
    github = tortilla.wrap('https://api.github.com', cache_lifetime=60)
    github_user = github.users.get(username)
    repos =  github.users(username).repos.get()
    skills_count = dict(Counter([repo['language'] for repo in repos]))
    Skill = namedtuple('Skill', "name level font_name")

    if skills_count.get(None):
        del skills_count[None]

    icon_replacements ={
        "CSS": "css3",
        "Shell": "linux",
        "Makefile": "linux",
        "HTML": "html5",
        "Puppet": "ruby",
        "Scala": "java",
        "VimL": "linux",
        "Haskell": "linux",
        "Clojure": "linux",
        "Elixir": "linux",
        "Arduino": "linux"
    }
    unsorted_skills = [
        Skill(name=skill[0], level=skill[1], font_name=icon_replacements.get(skill[0], skill[0]))
        for skill
        in skills_count.items()
    ]
    skills = sorted(unsorted_skills, key=lambda s: s.level, reverse=True)
    if len(skills) > 8:
        skills = skills[:8]
    elif len(skills) > 4:
        skills = skills[:4]

    gists = github.users(username).gists.get()
    return locals()
Пример #28
0
from flask import jsonify, abort, make_response, request
import requests
from requests.auth import HTTPDigestAuth
from flask.ext.httpauth import HTTPBasicAuth
from flask import Blueprint
import json
import tortilla

host = Blueprint('host',__name__)
auth = HTTPBasicAuth()
dominy = tortilla.wrap('http://127.0.0.1:8080/api')


@host.route('/check/<host>', methods=['GET','POST'])
def check(host):
    #if 'username' in session :
    #     return render_template('index.html')  # render a template
    if (host):
        dom = dominy.hostCheck.get(host)
        return jsonify(dom)
    return '{}'

@host.route('/update/<host>', methods=['GET','POST'])
def update(host):
    #if 'username' in session :
    #     return render_template('index.html')  # render a template
    if (host):
        dom = dominy.hostUpdate.put(host)
        return jsonify(dom)
    return '{}'
Пример #29
0
 def __init__(self) -> None:
     self.base_url = 'https://api.typeform.com/v0/'
     self.api_key  = os.environ['TYPEFORM_API_KEY']
     self.form_id  = os.environ['TYPEFORM_ID']
     self.api      = tortilla.wrap(self.base_url)
Пример #30
0
    # `quote` method of `urllib`. On Python 2, this can cause KeyErrors
    # when the string contains unicode. To prevent this, we encode the
    # string so urllib can safely quote it.
    from httpretty.core import url_fix
    def fixed_url_fix(s, charset='utf-8'):
        return url_fix(s.encode(charset), charset)
    httpretty.core.url_fix = fixed_url_fix


from tortilla.compat import is_py2
if is_py2:
    monkey_patch_httpretty()


API_URL = 'https://test.tortilla.locally'
api = tortilla.wrap(API_URL)


def register_urls(endpoints):
    for endpoint, options in six.iteritems(endpoints):
        if isinstance(options.get('body'), (dict, list, tuple)):
            body = json.dumps(options.get('body'))
        else:
            body = options.get('body')
        print(body, endpoint)
        httpretty.register_uri(method=options.get('method', 'GET'),
                               status=options.get('status', 200),
                               uri=API_URL + endpoint,
                               body=body)

Пример #31
0
def api():
    return tortilla.wrap(API_URL)
Пример #32
0
 def __init__(self, host, port, base_url, auth=None, protocol="http"):
     self.url = f"{protocol}://{host}:{port}/{base_url}"
     self.auth = auth
     self.header = [{"Content-Type": "application/json"}]
     # 使用tortilla来进行包装
     self.api = tortilla.wrap(self.url, headers=self.header)
Пример #33
0
            price = soupitem.select('div.price')[0].text.lstrip().rstrip()
        except:
            price = ''
        item = dict(title=soupitem['title'], url=soupitem['href'],
                    image=image, location=location, price=price)

        res.append(item)

    return res


if __name__=='__main__':

    tortilla.formats.register('leboncoin_xml', parse_leboncoin_result, xmltodict.unparse)

    lbc = tortilla.wrap('http://www.leboncoin.fr/', format='leboncoin_xml', delay=5)

    # recherche de sacs à dos sur Grenoble
    result = lbc('annonces').offres.get('rhone_alpes',
                            params=dict(f='a', th=1,
                                        q=u'sac à dos',
                                        location='Grenoble 38000,Grenoble 38100'))

    for item in result:
        show_item(item)

    # Recherche de ventes immobilières à Crolles et Bernin
    result = lbc('ventes_immobilieres').offres.get(
        'rhone_alpes',
        params=dict(f='a', th=1, q=u'',
                    location='Crolles 38190,Bernin 38190'))
from abc import ABCMeta, abstractmethod
from datetime import datetime
from collections import namedtuple
import re
import time
import os.path

import tortilla


__all__ = ['FootballData', 'Timeframe']

URL = 'http://api.football-data.org/alpha'

api = tortilla.wrap(URL)


#Results namedtuple so we can return result in an object
Results = namedtuple('Results', ['goalsHomeTeam', 'goalsAwayTeam'])


def requests_middleware(r, *args, **kwargs):
    """
    A middleware that edits the responses from the api.
    The api data contains the key "self" in various responses but using this breaks tortilla because it
    conflicts with python self. So we search and replace every key  "self" with "_self"
    """
    content = r.content.decode(r.encoding)
    content = content.replace('"self":', '"_self":')
    r._content = content.encode(r.encoding)
Пример #35
0
 def __init__(self, **kwargs):
     self.url = self._get_url()
     self.api = tortilla.wrap(self.url, headers=self.headers)
     self._client.session.mount('http://',
                                HTTPAdapter(max_retries=Retry(total=5)))
     self.body = None
Пример #36
0
from abc import ABCMeta, abstractmethod
from datetime import datetime
from collections import namedtuple
import re
import time
import os.path

import tortilla

__all__ = ['FootballData', 'Timeframe']

URL = 'http://api.football-data.org/alpha'

api = tortilla.wrap(URL)

#Results namedtuple so we can return result in an object
Results = namedtuple('Results', ['goalsHomeTeam', 'goalsAwayTeam'])


def requests_middleware(r, *args, **kwargs):
    """
    A middleware that edits the responses from the api.
    The api data contains the key "self" in various responses but using this breaks tortilla because it
    conflicts with python self. So we search and replace every key  "self" with "_self"
    """
    content = r.content.decode(r.encoding)
    content = content.replace('"self":', '"_self":')
    r._content = content.encode(r.encoding)

    #Sleep so we do not flood the server with requests
Пример #37
0
    # when the string contains unicode. To prevent this, we encode the
    # string so urllib can safely quote it.
    from httpretty.core import url_fix

    def fixed_url_fix(s, charset='utf-8'):
        return url_fix(s.encode(charset), charset)

    httpretty.core.url_fix = fixed_url_fix


from tortilla.compat import is_py2
if is_py2:
    monkey_patch_httpretty()

API_URL = 'https://test.tortilla.locally'
api = tortilla.wrap(API_URL)


def register_urls(endpoints):
    for endpoint, options in six.iteritems(endpoints):
        if isinstance(options.get('body'), (dict, list, tuple)):
            body = json.dumps(options.get('body'))
        else:
            body = options.get('body')
        httpretty.register_uri(method=options.get('method', 'GET'),
                               status=options.get('status', 200),
                               uri=API_URL + endpoint,
                               body=body)


with open('test_data.json') as resource:
Пример #38
0
                                                     |      +-------------------+
                                                     |
                                                     |      +-------------------+        +----------+
                                                     +------+ MEMBERSHIP        +--------+  PERSON  |
                                                            | role: Vicesindaco |        +----------+
                                                            +-------------------+

"""

popit = Popit(instance='pops3',
              host='popit.openpolis.it',
              user='******',
              password='******',
              api_key='705640d779cfee8c25d03911793c939266a9a761',
              debug=False)
pops = tortilla.wrap('http://*****:*****@openpolis")
exp = {
    "organizations": parties.results,
}
popit.api.post('imports', data=exp)

for a in areas.results:
Пример #39
0
 def __init__(self, in_username, in_password, expiration=60):
     self.agol = tortilla.wrap('https://www.arcgis.com')
     self.username = in_username
     self.password = in_password
     self.expiration = expiration
     self.token = self.gen_token()
Пример #40
0
import os, json
import tortilla
import srt
from dotenv import load_dotenv


def jsonPrint(data):
    print json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))


load_dotenv('.env')  # get envs

# amaraApiUrl = 'https://www.amara.org/api/'
amaraApiUrl = 'http://localhost:8000/api/'

api = tortilla.wrap(amaraApiUrl, suffix="/", debug=True)
api.config.headers['X-api-username'] = '******'
api.config.headers[
    'X-apikey'] = '9287f28dac7222531773940fc996e89ce35b8854'  #os.environ.get('amaraToken')
api.config.headers['Accept'] = 'application/json'

videoId = 'gPZUcxWUf7rc'
languageCode = 'en'

# videoInfo = api.videos(videoId).get()
# subtitles = api.videos(videoId).languages(languageCode).subtitles.get()
# jsonPrint(subtitles)


def createVideo(videoInfo):
    # create video - is not working now
Пример #41
0
def om_rest_collection_api(om_server, om_server_port):
    return tortilla.wrap('http://{}:{}/v1/inserterSMPPLinks'.format(
        om_server, om_server_port),
                         format='json')
Пример #42
0
api_sign = hmac.new(API_SECRET, '/api/v1/strategies',
                    hashlib.sha256).hexdigest()
'''
response = requests.get(
  'https://test.bmybit.com/api/v1/strategies',
  headers={
    'X-Api-Key': API_KEY,
    'X-Api-Sign': api_sign
  },
)

print response.content
'''

bmybit = tortilla.wrap('https://test.bmybit.com/api/v1')

bmybit.config.headers['X-Api-Key'] = API_KEY
bmybit.config.headers['api_sign'] = api_sign

print bmybit.config.headers

res = bmybit.get('strategies',
                 params={'id': 330},
                 headers={
                     'X-Api-Key': API_KEY,
                     'X-Api-Sign': api_sign
                 })

print res
Пример #43
0
 def __init__(self, in_username, in_password, expiration=60):
     self.agol = tortilla.wrap('https://www.arcgis.com')
     self.username = in_username
     self.password = in_password
     self.expiration = expiration
     self.token = self.gen_token()
Пример #44
0
def api():
    return tortilla.wrap(API_URL)
Пример #45
0
def om_rest_api(om_server, om_server_port):
    api = tortilla.wrap('http://{}:{}/v1/inserterSMPPLink'.format(om_server, om_server_port), format='json')
    api.config.headers = {'Content-Type': 'application/json'}
    return api
Пример #46
0
    def setUp(self):
        httpretty.enable()
        self.api = tortilla.wrap(API_URL)

        if self.endpoints is None:
            self.endpoints = setup()
Пример #47
0
def om_rest_api(om_server, om_server_port):
    api = tortilla.wrap('http://{}:{}/v1/inserterSMPPLink'.format(
        om_server, om_server_port),
                        format='json')
    api.config.headers = {'Content-Type': 'application/json'}
    return api
Пример #48
0
# http://jugad2.blogspot.sg/2014/12/tortilla-python-api-wrapper.html

import tortilla

github = tortilla.wrap('https://api.github.com')
user = github.users.get('feigaochn')

for key in user:
    print(key, ":", user[key])
Пример #49
0
def om_rest_collection_api(om_server, om_server_port):
    return tortilla.wrap('http://{}:{}/v1/inserterSMPPLinks'.format(om_server, om_server_port), format='json')