Python requests 模块,org() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用requests.org()

项目:biweeklybudget    作者:jantman    | 项目源码 | 文件源码
def chrome(self):
        # https://github.com/SeleniumHQ/selenium/blob/master/py/selenium/webdriver/remote/webdriver.py
        # http://www.guguncube.com/2983/python-testing-selenium-with-google-chrome
        # https://gist.github.com/addyosmani/5336747
        # http://blog.likewise.org/2015/01/setting-up-chromedriver-and-the-selenium-webdriver-python-bindings-on-ubuntu-14-dot-04/
        # https://sites.google.com/a/chromium.org/chromedriver/getting-started
        # http://stackoverflow.com/questions/8255929/running-webdriver-chrome-with-selenium
        chrome = webdriver.Chrome()
        return chrome

#     @property
#     def firefox(self):
#         profile = webdriver.FirefoxProfile()
#         #firefox = webdriver.Firefox(firefox_profile=profile)
#         firefox = WebDriver(firefox_profile=profile)
#         return firefox
项目:DropboxConnect    作者:raguay    | 项目源码 | 文件源码
def create_session(max_connections=8, proxies=None):
    """
    Creates a session object that can be used by multiple :class:`Dropbox` and
    :class:`DropboxTeam` instances. This lets you share a connection pool
    amongst them, as well as proxy parameters.

    :param int max_connections: Maximum connection pool size.
    :param dict proxies: See the `requests module
            <http://docs.python-requests.org/en/latest/user/advanced/#proxies>`_
            for more details.
    :rtype: :class:`requests.sessions.Session`. `See the requests module
        <http://docs.python-requests.org/en/latest/user/advanced/#session-objects>`_
        for more details.
    """
    # We only need as many pool_connections as we have unique hostnames.
    session = pinned_session(pool_maxsize=max_connections)
    if proxies:
        session.proxies = proxies
    return session
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def create_session(max_connections=8, proxies=None):
    """
    Creates a session object that can be used by multiple :class:`Dropbox` and
    :class:`DropboxTeam` instances. This lets you share a connection pool
    amongst them, as well as proxy parameters.


    :param int max_connections: Maximum connection pool size.
    :param dict proxies: See the `requests module
            <http://docs.python-requests.org/en/latest/user/advanced/#proxies>`_
            for more details.
    :rtype: :class:`requests.sessions.Session`. `See the requests module
        <http://docs.python-requests.org/en/latest/user/advanced/#session-objects>`_
        for more details.
    """
    # We only need as many pool_connections as we have unique hostnames.
    session = pinned_session(pool_maxsize=max_connections)
    if proxies:
        session.proxies = proxies
    return session
项目:automation-scripts    作者:meraki    | 项目源码 | 文件源码
def getshardhost(p_apikey, p_orgid):
    #Looks up shard URL for a specific org. Use this URL instead of 'dashboard.meraki.com'
    # when making API calls with API accounts that can access multiple orgs.
    #On failure returns 'null'

    time.sleep(API_EXEC_DELAY)
    try:
        r = requests.get('https://dashboard.meraki.com/api/v0/organizations/%s/snmp' % p_orgid, headers={'X-Cisco-Meraki-API-Key': p_apikey, 'Content-Type': 'application/json'})
    except:
        printusertext('ERROR 02: Unable to contact Meraki cloud')
        sys.exit(2)

    if r.status_code != requests.codes.ok:
        return 'null'

    rjson = r.json()

    return(rjson['hostname'])
项目:pep8speaks    作者:OrkoHunter    | 项目源码 | 文件源码
def _request(query=None, method="GET", json=None, data=None, headers=None, params=None):
    """
    Queries like /repos/:id needs to be appended to the base URL,
    Queries like https://raw.githubusercontent.com need not.

    full list of kwargs see http://docs.python-requests.org/en/master/api/#requests.request
    """

    if query[0] == "/":
        query = BASE_URL + query

    kwargs = {
        "auth": AUTH,
        "json": json if json else None,
        "data": data if data else None,
        "headers": headers if headers else None,
        "params": params if params else None,
    }
    return requests.request(method, query, **kwargs)
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_settings(greeting_text):
    """ Sets the START Button and also the Greeting Text.
        The payload for the START Button will be 'USER_START'

    :param str greeting_text: Desired Greeting Text (160 chars).
    :return: `Response object <http://docs.python-requests.org/en/\
    master/api/#requests.Response>`_
    """
    # Set the greeting texts
    url = TD_STS_URL + PAGE_ACCESS_TOKEN
    txtpayload = {}
    txtpayload['setting_type'] = 'greeting'
    txtpayload['greeting'] = {'text': greeting_text}
    response_msg = json.dumps(txtpayload)
    status = requests.post(url, headers=HEADER, data=response_msg)
    # Set the start button
    btpayload = {}
    btpayload['setting_type'] = 'call_to_actions'
    btpayload['thread_state'] = 'new_thread'
    btpayload['call_to_actions'] = [{'payload': 'USER_START'}]
    response_msg = json.dumps(btpayload)
    status = requests.post(url, headers=HEADER, data=response_msg)
    return status
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_start_button(payload='START'):
    """ Sets the Thread Settings Greeting Text
    (/docs/messenger-platform/thread-settings/get-started-button).

    :param str payload: Desired postback payload (Default START).
    :return: `Response object <http://docs.python-requests.org/en/\
    master/api/#requests.Response>`_
    """
    url = TD_STS_URL + PAGE_ACCESS_TOKEN
    btpayload = {}
    btpayload["setting_type"] = "call_to_actions"
    btpayload["thread_state"] = "new_thread"
    btpayload["call_to_actions"] = [{"payload": payload}]
    response_msg = json.dumps(btpayload)
    status = requests.post(url, headers=HEADER, data=response_msg)
    return status
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_domain_whitelisting(whitelisted_domains, domain_action_type='add'):
    """ Sets the whistelisted domains for the Messenger Extension
    (/docs/messenger-platform/thread-settings/domain-whitelisting).

    :param list whistelisted_domains: Domains to be whistelisted.
    :param str domain_action_type: Action to run `add/remove` (Defaut add).
    :return: `Response object <http://docs.python-requests.org/en/\
    master/api/#requests.Response>`_
    """
    url = TD_STS_URL + PAGE_ACCESS_TOKEN
    payload = {}
    payload['setting_type'] = 'domain_whitelisting'
    payload['whitelisted_domains'] = whitelisted_domains
    payload['domain_action_type'] = domain_action_type
    data = json.dumps(payload)
    status = requests.post(url, headers=HEADER, data=data)
    return status
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def typing(fbid, sender_action):
    """ Displays/Hides the typing gif/mark seen on facebook chat
    (/docs/messenger-platform/send-api-reference/sender-actions)

    :param str fbid: User id to display action.
    :param str sender_action: `typing_off/typing_on/mark_seen`.
    :return: `Response object <http://docs.python-requests.org/en/\
    master/api/#requests.Response>`_
    """
    url = MSG_URL + PAGE_ACCESS_TOKEN
    payload = {}
    payload['recipient'] = {'id': fbid}
    payload['sender_action'] = sender_action
    data = json.dumps(payload)
    status = requests.post(url, headers=HEADER, data=data)
    return status


# Send API Content Type
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_text_message(fbid, message):
    """ Sends a common text message
    (/docs/messenger-platform/send-api-reference/text-message)

    :param str fbid: User id to send the text.
    :param str message: Text to be displayed for the user (230 chars).
    :return: `Response object <http://docs.python-requests.org/en/\
    master/api/#requests.Response>`_
    """
    url = MSG_URL + PAGE_ACCESS_TOKEN
    payload = {}
    payload['recipient'] = {'id': fbid}
    payload['message'] = {'text': message}  # Limit 320 chars
    data = json.dumps(payload)
    status = requests.post(url, headers=HEADER, data=data)
    return status
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_attachment(fbid, media_url, file_type):
    """ Sends a media attachment
    (/docs/messenger-platform/send-api-reference/contenttypes)

    :param str fbid: User id to send the audio.
    :param str url: Url of a hosted media.
    :param str type: image/audio/video/file.
    :return: `Response object <http://docs.python-requests.org/en/\
    master/api/#requests.Response>`_
    """
    url = MSG_URL + PAGE_ACCESS_TOKEN
    payload = {}
    payload['recipient'] = {'id': fbid}
    attachment = {"type": file_type, "payload": {"url": media_url}}
    payload['message'] = {"attachment": attachment}
    data = json.dumps(payload)
    status = requests.post(url, headers=HEADER, data=data)
    return status
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_start_button(payload='START'):
    """ Sets the **Get Started button**.

    :usage:

        >>> payload = 'GET_STARTED'
        >>> response = fbbotw.post_start_button(payload=payload)
    :param str payload: Desired postback payload (Default 'START').
    :return: `Response object <http://docs.python-requests.org/en/\
    master/api/#requests.Response>`_
    :facebook docs: `/get-started-button <https://developers.facebook\
    .com/docs/messenger-platform/messenger-profile/get-started-button>`_
    """
    url = MESSENGER_PROFILE_URL.format(access_token=PAGE_ACCESS_TOKEN)
    payload_data = {}
    payload_data['get_started'] = {'payload': payload}
    data = json.dumps(payload_data)
    status = requests.post(url, headers=HEADER, data=data)
    return status
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_domain_whitelist(whitelisted_domains):
    """ Sets the whistelisted domains for the Messenger Extension

    :usage:

        >>> # Define the array of domains to be whitelisted (Max 10)
        >>> whistelisted_domains = [
                "https://myfirst_domain.com",
                "https://another_domain.com"
            ]
        >>> fbbotw.post_domain_whitelist(
                whitelisted_domains=whitelisted_domains
            )
    :param list whistelisted_domains: Domains to be whistelisted (Max 10).
    :return: `Response object <http://docs.python-requests.org/en/\
    master/api/#requests.Response>`_
    :facebook docs: `/domain-whitelisting <https://developers.facebook.\
    com/docs/messenger-platform/messenger-profile/domain-whitelisting>`_
    """
    url = MESSENGER_PROFILE_URL.format(access_token=PAGE_ACCESS_TOKEN)
    payload = {}
    payload['whitelisted_domains'] = whitelisted_domains
    data = json.dumps(payload)
    status = requests.post(url, headers=HEADER, data=data)
    return status
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_account_linking_url(account_linking_url):
    """ Sets the **liking_url** to connect the user with your business login

    :usage:

        >>> my_callback_linking_url = "https://my_business_callback.com"
        >>> response = fbbotw.post_account_linking_url(
                account_linking_url=my_callback_linking_url
            )
    :param str account_linking_url: URL to the account linking OAuth flow.
    :return: `Response object <http://docs.python-requests.org/en/\
    master/api/#requests.Response>`_
    :facebook docs: `/account-linking-url <https://developers.facebook.\
    com/docs/messenger-platform/messenger-profile/account-linking-url>`_
    """
    url = MESSENGER_PROFILE_URL.format(access_token=PAGE_ACCESS_TOKEN)
    payload = {}
    payload['account_linking_url'] = account_linking_url
    data = json.dumps(payload)
    status = requests.post(url, headers=HEADER, data=data)
    return status
项目:qinling    作者:openstack    | 项目源码 | 文件源码
def __init__(self, conf):
        self.conf = conf

        client.Configuration().host = self.conf.kubernetes.kube_host
        self.v1 = client.CoreV1Api()
        self.v1extention = client.ExtensionsV1beta1Api()

        # Create namespace if not exists
        self._ensure_namespace()

        # Get templates.
        template_loader = jinja2.FileSystemLoader(
            searchpath=os.path.dirname(TEMPLATES_DIR)
        )
        jinja_env = jinja2.Environment(
            loader=template_loader, autoescape=True, trim_blocks=True,
            lstrip_blocks=True
        )
        self.deployment_template = jinja_env.get_template('deployment.j2')
        self.service_template = jinja_env.get_template('service.j2')
        self.pod_template = jinja_env.get_template('pod.j2')

        # Refer to
        # http://docs.python-requests.org/en/master/user/advanced/#session-objects
        self.session = requests.Session()
项目:Liljimbo-Chatbot    作者:chrisjim316    | 项目源码 | 文件源码
def speech(self, audio_file, verbose=None, headers=None):
        """ Sends an audio file to the /speech API.
        Uses the streaming feature of requests (see `req`), so opening the file
        in binary mode is strongly reccomended (see
        http://docs.python-requests.org/en/master/user/advanced/#streaming-uploads).
        Add Content-Type header as specified here: https://wit.ai/docs/http/20160526#post--speech-link

        :param audio_file: an open handler to an audio file
        :param verbose:
        :param headers: an optional dictionary with request headers
        :return:
        """
        params = {}
        headers = headers or {}
        if verbose:
            params['verbose'] = True
        resp = req(self.logger, self.access_token, 'POST', '/speech', params,
                   data=audio_file, headers=headers)
        return resp
项目:joesandboxcloudapi    作者:joesecurity    | 项目源码 | 文件源码
def __init__(self, apikey=API_KEY, apiurl=API_URL, accept_tac=ACCEPT_TAC, timeout=None, verify_ssl=True, retries=3, proxies=None):
        """
        Create a JoeSandbox object.

        Parameters:
          apikey:     the api key
          apiurl:     the api url
          accept_tac: Joe Sandbox Cloud requires accepting the Terms and Conditions.
                      https://jbxcloud.joesecurity.org/resources/termsandconditions.pdf
          timeout:    Timeout in seconds for accessing the API. Raises a ConnectionError on timeout.
          verify_ssl: Enable or disable checking SSL certificates.
          retries:    Number of times requests should be retried if they timeout.
          proxies:    Proxy settings, see the requests library for more information:
                      http://docs.python-requests.org/en/master/user/advanced/#proxies
        """
        self.apikey = apikey
        self.apiurl = apiurl.rstrip("/")
        self.accept_tac = accept_tac
        self.timeout = timeout
        self.retries = retries

        self.session = requests.Session()
        self.session.verify = verify_ssl
        self.session.proxies = proxies
项目:AppBackend    作者:540871129    | 项目源码 | 文件源码
def call_api(self, action, params=None, **kwargs):
        """
        ??API????????SSL?????????

        http://www.python-requests.org/en/latest/user/advanced/#ssl-cert-verification

        :param action: Method Name?
        :param params: Dictionary,form params for api.
        :param timeout: (optional) Float describing the timeout of the request.
        :return:
        """
        return self._http_call(
            url=self._join_url(self.api_host, "%s.%s" % (action, self.response_type)),
            method="POST",
            data=params,
            headers=self._headers(),
            **kwargs
        )
项目:ise    作者:bobthebutcher    | 项目源码 | 文件源码
def __init__(self, ise_node, ers_user, ers_pass, verify=False, disable_warnings=False, timeout=2):
        """
        Class to interact with Cisco ISE via the ERS API
        :param ise_node: IP Address of the primary admin ISE node
        :param ers_user: ERS username
        :param ers_pass: ERS password
        :param verify: Verify SSL cert
        :param disable_warnings: Disable requests warnings
        :param timeout: Query timeout
        """
        self.ise_node = ise_node
        self.user_name = ers_user
        self.user_pass = ers_pass

        self.url_base = 'https://{0}:9060/ers'.format(self.ise_node)
        self.ise = requests.session()
        self.ise.auth = (self.user_name, self.user_pass)
        self.ise.verify = verify  # http://docs.python-requests.org/en/latest/user/advanced/#ssl-cert-verification
        self.disable_warnings = disable_warnings
        self.timeout = timeout
        self.ise.headers.update({'Connection': 'keep_alive'})

        if self.disable_warnings:
            requests.packages.urllib3.disable_warnings()
项目:drupebox    作者:duncanhawthorne    | 项目源码 | 文件源码
def create_session(max_connections=8, proxies=None):
    """
    Creates a session object that can be used by multiple :class:`Dropbox` and
    :class:`DropboxTeam` instances. This lets you share a connection pool
    amongst them, as well as proxy parameters.

    :param int max_connections: Maximum connection pool size.
    :param dict proxies: See the `requests module
            <http://docs.python-requests.org/en/latest/user/advanced/#proxies>`_
            for more details.
    :rtype: :class:`requests.sessions.Session`. `See the requests module
        <http://docs.python-requests.org/en/latest/user/advanced/#session-objects>`_
        for more details.
    """
    # We only need as many pool_connections as we have unique hostnames.
    session = pinned_session(pool_maxsize=max_connections)
    if proxies:
        session.proxies = proxies
    return session
项目:bots    作者:nemobis    | 项目源码 | 文件源码
def get_doi_el(wiki, dbcnf):
    """ Set of DOI codes from external links. """

    dois = set([])

    doiquery = """SELECT el_to
    FROM externallinks
    WHERE el_index LIKE 'https://org.doi.dx./10%'
    OR el_index LIKE 'http://org.doi.dx./10%'"""

    with get_connection(wiki, dbcnf) as connection:
        cursor = connection.cursor()
        cursor.execute(doiquery)
        for link in cursor.fetchall():
            try:
                doi = re.findall('10.+$', link[0].decode('utf-8'))[0]
                if doi:
                    dois.add(unquote(doi))
            except IndexError:
                continue

    # print "Found %d DOI external links on %s" % (len(dois), wiki)
    return dois
项目:bots    作者:nemobis    | 项目源码 | 文件源码
def get_doai_oa(doi):
    """ Given a DOI, return DOAI target URL if green open access,
        None otherwise.
    """

    doaiurl = 'http://doai.io/{}'.format(doi)
    try:
        doai = SESSIONDOAI.head(url=doaiurl)
    except requests.ConnectionError:
        time.sleep(random.randint(1, 100))
        return False

    if doai.status_code == 302:
        url = doai.headers['Location']
        if re.search('doi.org', url):
            return None
        else:
            return url
项目:Pi_Physical_Dashboard    作者:adafruit    | 项目源码 | 文件源码
def message(client, feed_id, payload):
    # Message function will be called when a subscribed feed has a new value.
    # The feed_id parameter identifies the feed, and the payload parameter has
    # the new value.
    print('Feed {0} received new value: {1}'.format(feed_id, payload))
    # Update physical dashboard depending on the changed feed.
    # Notice the feed_id is checked to find out which feed changed, then the
    # appropriate physical dashboard widget is changed.
    if feed_id == 'pi-dashboard-slider':
        # The requests.post function will make an HTTP request against the
        # dashboard.  See the requests documentation for more information:
        #   http://docs.python-requests.org/en/latest/
        requests.post('{0}/widgets/slider'.format(DASHBOARD_URL), data={'value': payload})
    elif feed_id == 'pi-dashboard-humidity':
        requests.post('{0}/widgets/humidity'.format(DASHBOARD_URL), data={'value': payload})
    elif feed_id == 'pi-dashboard-temp':
        requests.post('{0}/widgets/temp'.format(DASHBOARD_URL), data={'value': payload})


# Create an MQTT client instance.
项目:deb-python-httpretty    作者:openstack    | 项目源码 | 文件源码
def test_multiline():
    url = 'http://httpbin.org/post'
    data = b'content=Im\r\na multiline\r\n\r\nsentence\r\n'
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
        'Accept': 'text/plain',
    }
    HTTPretty.register_uri(
        HTTPretty.POST,
        url,
    )
    response = requests.post(url, data=data, headers=headers)

    expect(response.status_code).to.equal(200)
    expect(HTTPretty.last_request.method).to.equal('POST')
    expect(HTTPretty.last_request.path).to.equal('/post')
    expect(HTTPretty.last_request.body).to.equal(data)
    expect(HTTPretty.last_request.headers['content-length']).to.equal('37')
    expect(HTTPretty.last_request.headers['content-type']).to.equal('application/x-www-form-urlencoded; charset=utf-8')
    expect(len(HTTPretty.latest_requests)).to.equal(1)
项目:deb-python-httpretty    作者:openstack    | 项目源码 | 文件源码
def test_octet_stream():
    url = 'http://httpbin.org/post'
    data = b"\xf5\x00\x00\x00"  # utf-8 with invalid start byte
    headers = {
        'Content-Type': 'application/octet-stream',
    }
    HTTPretty.register_uri(
        HTTPretty.POST,
        url,
    )
    response = requests.post(url, data=data, headers=headers)

    expect(response.status_code).to.equal(200)
    expect(HTTPretty.last_request.method).to.equal('POST')
    expect(HTTPretty.last_request.path).to.equal('/post')
    expect(HTTPretty.last_request.body).to.equal(data)
    expect(HTTPretty.last_request.headers['content-length']).to.equal('4')
    expect(HTTPretty.last_request.headers['content-type']).to.equal('application/octet-stream')
    expect(len(HTTPretty.latest_requests)).to.equal(1)
项目:deb-python-httpretty    作者:openstack    | 项目源码 | 文件源码
def test_multipart():
    url = 'http://httpbin.org/post'
    data = b'--xXXxXXyYYzzz\r\nContent-Disposition: form-data; name="content"\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: 68\r\n\r\nAction: comment\nText: Comment with attach\nAttachment: x1.txt, x2.txt\r\n--xXXxXXyYYzzz\r\nContent-Disposition: form-data; name="attachment_2"; filename="x.txt"\r\nContent-Type: text/plain\r\nContent-Length: 4\r\n\r\nbye\n\r\n--xXXxXXyYYzzz\r\nContent-Disposition: form-data; name="attachment_1"; filename="x.txt"\r\nContent-Type: text/plain\r\nContent-Length: 4\r\n\r\nbye\n\r\n--xXXxXXyYYzzz--\r\n'
    headers = {'Content-Length': '495', 'Content-Type': 'multipart/form-data; boundary=xXXxXXyYYzzz', 'Accept': 'text/plain'}
    HTTPretty.register_uri(
        HTTPretty.POST,
        url,
    )
    response = requests.post(url, data=data, headers=headers)
    expect(response.status_code).to.equal(200)
    expect(HTTPretty.last_request.method).to.equal('POST')
    expect(HTTPretty.last_request.path).to.equal('/post')
    expect(HTTPretty.last_request.body).to.equal(data)
    expect(HTTPretty.last_request.headers['content-length']).to.equal('495')
    expect(HTTPretty.last_request.headers['content-type']).to.equal('multipart/form-data; boundary=xXXxXXyYYzzz')
    expect(len(HTTPretty.latest_requests)).to.equal(1)
项目:deb-python-httpretty    作者:openstack    | 项目源码 | 文件源码
def test_httpretty_allows_to_chose_if_querystring_should_be_matched():
    "HTTPretty should provide a way to not match regexes that have a different querystring"

    HTTPretty.register_uri(
        HTTPretty.GET,
        re.compile("https://example.org/(?P<endpoint>\w+)/$"),
        body="Nudge, nudge, wink, wink. Know what I mean?",
        match_querystring=True
    )

    response = requests.get('https://example.org/what/')
    expect(response.text).to.equal('Nudge, nudge, wink, wink. Know what I mean?')
    try:
        requests.get('https://example.org/what/?flying=coconuts')
        raised = False
    except requests.ConnectionError:
        raised = True

    assert raised is True
项目:firebase-admin-python    作者:firebase    | 项目源码 | 文件源码
def _request(self, method, urlpath, **kwargs):
        """Makes an HTTP call using the Python requests library.

        Refer to http://docs.python-requests.org/en/master/api/ for more information on supported
        options and features.

        Args:
          method: HTTP method name as a string (e.g. get, post).
          urlpath: URL path of the remote endpoint. This will be appended to the server's base URL.
          kwargs: An additional set of keyword arguments to be passed into requests API
              (e.g. json, params).

        Returns:
          dict: The parsed JSON response.
        """
        resp = self._session.request(method, ID_TOOLKIT_URL + urlpath, **kwargs)
        resp.raise_for_status()
        return resp.json()
项目:firebase-admin-python    作者:firebase    | 项目源码 | 文件源码
def request(self, method, url, **kwargs):
        """Makes an HTTP call using the Python requests library.

        This is the sole entry point to the requests library. All other helper methods in this
        class call this method to send HTTP requests out. Refer to
        http://docs.python-requests.org/en/master/api/ for more information on supported options
        and features.

        Args:
          method: HTTP method name as a string (e.g. get, post).
          url: URL of the remote endpoint.
          kwargs: An additional set of keyword arguments to be passed into the requests API
              (e.g. json, params).

        Returns:
          Response: An HTTP response object.

        Raises:
          RequestException: Any requests exceptions encountered while making the HTTP call.
        """
        resp = self._session.request(method, self._base_url + url, **kwargs)
        resp.raise_for_status()
        return resp
项目:cartoframes    作者:CartoDB    | 项目源码 | 文件源码
def _add_encoded_geom(df, geom_col):
    """Add encoded geometry to DataFrame"""
    # None if not a GeoDataFrame
    is_geopandas = getattr(df, '_geometry_column_name', None)
    if is_geopandas is None and geom_col is None:
        warn('`encode_geom` works best with Geopandas '
             '(http://geopandas.org/) and/or shapely '
             '(https://pypi.python.org/pypi/Shapely).')
        geom_col = 'geometry' if 'geometry' in df.columns else None
        if geom_col is None:
            raise KeyError('Geometries were requested to be encoded '
                           'but a geometry column was not found in the '
                           'DataFrame.'.format(geom_col=geom_col))
    elif is_geopandas and geom_col:
        warn('Geometry column of the input DataFrame does not '
             'match the geometry column supplied. Using user-supplied '
             'column...\n'
             '\tGeopandas geometry column: {}\n'
             '\tSupplied `geom_col`: {}'.format(is_geopandas,
                                                geom_col))
    elif is_geopandas and geom_col is None:
        geom_col = is_geopandas
    # updates in place
    df['the_geom'] = df[geom_col].apply(_encode_geom)
    return None
项目:mapillary-osm-usage-notification-bot    作者:ltog    | 项目源码 | 文件源码
def post_comments_to_mapillary(entries):
    global mapillary_client_id
    global mapillary_access_token
    global user_agent
    global time_out

    for e in entries:
        msg = "This image was mentioned on OpenStreetMap at https://www.openstreetmap.org/" + e.osmtype + "/" + e.osmid + " by user '" + e.osmuser + "'. Message generated by https://github.com/ltog/mapillary-osm-usage-notification-bot ."

        url = "https://a.mapillary.com/v2/im/" + e.mapillaryid + "/cm?client_id=" + mapillary_client_id
        payload = {"cm": msg}
        r = backoff_post(url, payload)
        logging.info("Posting comment for image " + e.mapillaryid + " resulted in HTTP status " + str(r.status_code) + " and response: " + r.text)
        if r.status_code == 200:
            log_success(str(e))
        if r.status_code == 404:
            logging.warning("Entry " + str(e) + "generated HTTP error 404 for URL " + url + " . ")
            log_failure(str(e))
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def main():
    # Start a session so we can have persistant cookies

    # Session() &gt;&gt; http://docs.python-requests.org/en/latest/api/#request-sessions
    session = requests.Session()

    # This is the form data that the page sends when logging in

    login_data = {
    'username': RegisterNumber,
    'password': DateofBirth,
    'submit': 'id',
    }
    print login_data

    # Authenticate
    r = session.post(URL, data = login_data)

    # Try accessing a page that requires you to be logged in
    r = session.get('http://sdpdr.nic.in/annauniv/result')

    web = QWebView()
    web.load(QUrl("http://sdpdr.nic.in/annauniv/result"))
    #web.show()

    printer = QPrinter()
    printer.setPageSize(QPrinter.A4)
    printer.setOutputFormat(QPrinter.PdfFormat)
    printer.setOutputFileName("result.pdf")

# convertion of page to pdf format
项目:automation-scripts    作者:meraki    | 项目源码 | 文件源码
def printhelp():
    #prints help text

    printusertext('This is a script to send an email alert if APs are in invalid management subnets. The alert is')
    printusertext(' sent using a SMTP server; by  default Gmail. Use an automation platform like Zapier to read this email')
    printusertext(' and trigger further actions.')
    printusertext('')
    printusertext('To run the script, enter:')
    printusertext(' python checksubnets.py -k <key> -v <valid subs> [-u <user> -p <pass> -d <dest>] [-s <srv> -o <org>]')
    printusertext('')
    printusertext('Mandatory arguments:')
    printusertext(' -k <key>             : Your Meraki Dashboard API key')
    printusertext(' -v <valid subs>      : List of valid management subnets. Alert if management IP is not in these')
    printusertext('Arguments to enable sending emails. All three must be given to send email. If omitted, print to screen:')
    printusertext(' -u <user>            : The username (email address) that will be used to send the alert message')
    printusertext(' -p <pass>            : Password for the email address where the message is sent from')
    printusertext(' -d <dest>            : Recipient email address')
    printusertext('Optional arguments:')
    printusertext(' -s <server>          : Server to use for sending SMTP. If omitted, Gmail will be used')
    printusertext(' -o <org>             : Name of organization to be processed. If omitted, will process all organizations')
    printusertext('')
    printusertext('Defining subnets:')
    printusertext(' Parameter "-v <valid subs>" can take subnets in the following forms:')
    printusertext(' <subnet>/<mask>,<subnet>/<mask>,<subnet>/<mask>      Example: -v 192.168.128.0/24,10.10.0.0/16')
    printusertext(' file:<filename>                                      Example: -v file:validsubs.txt')
    printusertext('  <filename> is the name of a text file that defines the valid subnets. Enter one subnet per line')
    printusertext('  in the form <subnet>/<mask>')
    printusertext('')
    printusertext('To make script chaining easier, all lines containing informational messages to the user')
    printusertext(' start with the character @')
    printusertext('')
    printusertext('In Windows, use double quotes ("") to pass arguments containing spaces.')
项目:tecken    作者:mozilla-services    | 项目源码 | 文件源码
def requests_retry_session(
    retries=3,
    backoff_factor=0.3,
    status_forcelist=(500, 502, 504),
):
    """Opinionated wrapper that creates a requests session with a
    HTTPAdapter that sets up a Retry policy that includes connection
    retries.

    If you do the more naive retry by simply setting a number. E.g.::

        adapter = HTTPAdapter(max_retries=3)

    then it will raise immediately on any connection errors.
    Retrying on connection errors guards better on unpredictable networks.
    From http://docs.python-requests.org/en/master/api/?highlight=retries#requests.adapters.HTTPAdapter
    it says: "By default, Requests does not retry failed connections."

    The backoff_factor is documented here:
    https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html#urllib3.util.retry.Retry
    A default of retries=3 and backoff_factor=0.3 means it will sleep like::

        [0.3, 0.6, 1.2]
    """  # noqa
    session = requests.Session()
    retry = Retry(
        total=retries,
        read=retries,
        connect=retries,
        backoff_factor=backoff_factor,
        status_forcelist=status_forcelist,
    )
    adapter = HTTPAdapter(max_retries=retry)
    session.mount('http://', adapter)
    session.mount('https://', adapter)
    return session
项目:rasp    作者:anidata    | 项目源码 | 文件源码
def get_page_source(self, url,
                        params=None,
                        headers=None):
        """Fetches the specified url.

        Attributes:
            url (str): The url of which to fetch the page source code.
            params (dict, optional): Key\:Value pairs to be converted to
                x-www-form-urlencoded url parameters_.
            headers (dict, optional): Extra headers to be merged into
                base headers for current Engine before requesting url.
        Returns:
            ``rasp.base.Webpage`` if successful

        .. _parameters: http://docs.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls
        """
        if not url:
            raise ValueError('url needs to be specified')

        if self.callback: self.callback()

        merged_headers = deepcopy(self.headers)
        if isinstance(headers, dict):
            merged_headers.update(headers)

        response = self.session.get(
            url, params=params, headers=merged_headers
        )
        return Webpage(
            url,
            source=response.text,
            headers=response.headers,
            response_code=response.status_code
        )
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_greeting_text(greeting_text):
    """ Sets the Thread Settings Greeting Text
    (/docs/messenger-platform/thread-settings/greeting-text).

    :param str greeting_text: Desired Greeting Text (160 chars)
    :return: `Response object <http://docs.python-requests.org/en/\
    master/api/#requests.Response>`_
    """
    url = TD_STS_URL + PAGE_ACCESS_TOKEN
    payload = {}
    payload["setting_type"] = "greeting"
    payload["greeting"] = {"text": greeting_text}
    response_msg = json.dumps(payload)
    status = requests.post(url, headers=HEADER, data=response_msg)
    return status
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_persistent_menu(call_to_actions):
    """ Sets a persistent menu on the chat
    (/docs/messenger-platform/thread-settings/persistent-menu)

    :param list call_to_actions: format :

        >>> call_to_actions =  [
            {
                'type': 'postback',
                'title': 'About',
                'payload': 'ABOUT'
            },
            {
                'type': 'web_url',
                'title': 'Google it',
                'url': 'https://www.google.com',
                'webview_height_ratio': 'full',
                'messenger_extensions': True
            },
        ]
    :return: `Response object <http://docs.python-requests.org/en/\
  master/api/#requests.Response>`_
    """
    url = TD_STS_URL + PAGE_ACCESS_TOKEN
    payload = {}
    payload["setting_type"] = "call_to_actions"
    payload["thread_state"] = "existing_thread"
    payload["call_to_actions"] = call_to_actions
    data = json.dumps(payload)
    status = requests.post(url, headers=HEADER, data=data)
    return status
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_text_list(fbid, messages=[]):
    """ Sends a serie of messages from list of text.

    :param str fbid: User id to send the text list.
    :param list messages: A list of messages to be sent.
    :return: A list of `Response objects <http://docs.python-\
    requests.org/en/master/api/#requests.Response>`_\
    for every message sent.
    """
    responses = []
    for msg in messages:
        responses.append(post_text_message(fbid=fbid, message=msg))
    return responses
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_audio_attachment(fbid, audio_url):
    """ Sends an audio attachment
    (/docs/messenger-platform/send-api-reference/audio-attachment)

    :param str fbid: User id to send the audio.
    :param str audio_url: Url of a hosted audio (10 Mb).
    :return: `Response object <http://docs.python-requests.org/en/\
    master/api/#requests.Response>`_
    """
    return post_attachment(fbid, audio_url, 'audio')
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_image_attachment(fbid, img_url):
    """ Sends an image attachment
    (/docs/messenger-platform/send-api-reference/image-attachment)

    :param str fbid: User id to send the image.
    :param str img_url: Url of a hosted image (jpg, png, gif).
    :return: `Response object <http://docs.python-requests.org/en/\
    master/api/#requests.Response>`_
    """
    return post_attachment(fbid, img_url, 'image')
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_video_attachment(fbid, video_url):
    """ Sends a video attachment
    (/docs/messenger-platform/send-api-reference/video-attachment)

    :param str fbid: User id to send the video.
    :param str video_url: Url of a hosted video.
    :return: `Response object <http://docs.python-requests.org/en/\
    master/api/#requests.Response>`_
    """
    return post_attachment(fbid, video_url, 'video')


# Send API Quick Replies
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_text_w_quickreplies(fbid, message, quick_replies):
    """ Send text with quick replies buttons
    (/docs/messenger-platform/send-api-reference/quick-replies).

    :param str fbid: User id to send the quick replies menu.
    :param str message: message to be displayed with the menu.
    :param list quick_replies: (Max 10) format :

        >>> quick_replies = [
            {
                "content_type": "text",
                "title": "Yes!",
                "payload": "USER_SAY_YES"
            },
            {
                "content_type": "text",
                "title": "Nope",
                "payload": "USER_SAY_NOT"
            }
        ]
    :return: `Response object <http://docs.python-requests.org/en/\
    master/api/#requests.Response>`_
    """
    url = MSG_URL + PAGE_ACCESS_TOKEN
    payload = {}
    payload["recipient"] = {"id": fbid}
    payload["message"] = {"text": message, "quick_replies": quick_replies}
    data = json.dumps(payload)
    status = requests.post(url, headers=HEADER, data=data)
    return status


# Send API Templates
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_button_template(fbid, text, buttons):
    """ Sends a button template with the specified text and buttons
    (/docs/messenger-platform/send-api-reference/button-template).

    :param str fbid: User id to send the buttons.
    :param str text: Message to be displayed with the buttons (320 Chars).
    :param list buttons: Dict of buttons that appear as call-to-actions, \
    format :

        >>> buttons = [
            {
                'type': 'web_url',
                'url': 'https://petersapparel.parseapp.com',
                'title': 'Show Website'
            },
            {
                'type': 'postback',
                'title': 'Start Chatting',
                'payload': 'USER_DEFINED_PAYLOAD'
            }
        ]
    :return: `Response object <http://docs.python-requests.org/en/\
    master/api/#requests.Response>`_.
    """
    url = MSG_URL + PAGE_ACCESS_TOKEN
    data = {}
    data['recipient'] = {'id': fbid}
    payload = {}
    payload['template_type'] = 'button'
    payload['text'] = text
    payload['buttons'] = buttons
    attachment = {"type": 'template', "payload": payload}
    data['message'] = {"attachment": attachment}
    data = json.dumps(data)
    status = requests.post(url, headers=HEADER, data=data)
    return status
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_call_button(fbid, text, title, phone_number):
    """ Sends a call button for the specified user
    (/docs/messenger-platform/send-api-reference/call-button).

    :param str fbid: User id to send the call button
    :param str text: Text to send with the button (Max 160 Chars).
    :param str title: Button title (Max 20 Chars).
    :param str phone_number: Format must have "+" prefix followed by\
    the country code, area code and local number.\
    For example, **+16505551234**.
    :return: `Response object <http://docs.python-requests.org/en/\
    master/api/#requests.Response>`_
    """
    url = MSG_URL + PAGE_ACCESS_TOKEN
    data = {}
    data['recipient'] = {'id': fbid}
    payload = {}
    payload['template_type'] = 'button'
    payload['text'] = text
    button = {}
    button['type'] = 'phone_number'
    button['title'] = title
    button['payload'] = phone_number
    payload['buttons'] = [button]
    attachment = {"type": "template", "payload": payload}
    data['message'] = {"attachment": attachment}
    data = json.dumps(data)
    status = requests.post(url, headers=HEADER, data=data)
    return status
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_settings(greeting_text):
    """ Sets the **Get Started** Button and the **Greeting Text** at once.
    The payload for the **Get Started** Button will be `USER_START`.

    :usage:

        >>> # Create a default greeting text (160 chars limit)
        >>> greeting_text = "Hello! I'm your bot!"
        >>> responses = fbbotw.post_settings(
                greeting_text=greeting_text
            )
    :param str greeting_text: Desired Greeting Text (160 chars).
    :return: tuple with two `Response object <http://docs.python-requests.\
    org/en/master/api/#requests.Response>`_ for the greeting \
    text and start button.
    """
    # Set the greeting texts
    url = THREAD_SETTINGS_URL.format(access_token=PAGE_ACCESS_TOKEN)
    txtpayload = {}
    txtpayload['setting_type'] = 'greeting'
    txtpayload['greeting'] = {'text': greeting_text}
    data = json.dumps(txtpayload)
    greeting_text_status = requests.post(
        url, headers=HEADER, data=data
    )
    # Set the start button
    url = MESSENGER_PROFILE_URL.format(access_token=PAGE_ACCESS_TOKEN)
    btpayload = {}
    btpayload['get_started'] = {'payload': 'USER_START'}
    data = json.dumps(btpayload)
    get_started_button_status = requests.post(
        url, headers=HEADER, data=data
    )
    return (greeting_text_status, get_started_button_status)
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_payment_settings(privacy_url="", public_key="", test_users=[]):
    """ Sets the configuration for payment: privacy policy url,
    public key or test users. At least one parameter should be passed
    in this function.

    :param str privacy_url: The payment_privacy_url will appear in \
    our payment dialogs.
    :param str public_key: The payment_public_key is used to encrypt \
    sensitive payment data sent to you. (Read payment reference on the \
    docs)
    :param list test_users: You can add payment test users \
    (user page-scoped id) so that their credit card won't be \
    charged during your development.
    :return: `Response object <http://docs.python-requests.org/en/\
    master/api/#requests.Response>`_
    :facebook docs: `/payment-settings <https://developers.facebook.\
    com/docs/messenger-platform/messenger-profile/payment-settings>`_
    """
    if any([privacy_url.strip(), public_key.strip(), test_users]):
        url = MESSENGER_PROFILE_URL.format(access_token=PAGE_ACCESS_TOKEN)
        payload = {"payment_settings": {}}
        if bool(privacy_url.strip()):
            payload['payment_settings']['privacy_url'] = privacy_url
        if bool(public_key.strip()):
            payload['payment_settings']['public_key'] = public_key
        if bool(test_users):
            payload['payment_settings']['testers'] = test_users
        data = json.dumps(payload)
        status = requests.post(url, headers=HEADER, data=data)
        return status
    return {"Error": "At least one parameter should be set"}
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_target_audience(countries, audience_type="all"):
    """ Set the audience who will see your bot in the Discover tab \
    on Messenger.

    :usage:
        >>> # If you will set the audience to specific contries
        >>> # The audience_type param should be set to 'custom'
        >>> audience_type = "custom"
        >>> countries = {
                "whitelist": ["US", "UK", "CA", "BR"]
            }
        >>> response = fbbotw.post_target_audience(
                countries=countries,
                audience_type=audience_type
            )
    :param dict countries: Country object with whitelist/blacklist. Needs\
    to be specified only when audience_type is 'custom'. Countries should \
    be in list of ISO 3166 Alpha-2 codes. format:

        >>> countries = {
            "whitelist": ["US", "BR"]
            "blacklist": []
        }
    :param str audience_type: ("all", "custom", "none"). Default: "all"
    :return: `Response object <http://docs.python-requests.org/en/\
    master/api/#requests.Response>`_
    :facebook docs: `/target-audience <https://developers.facebook.\
    com/docs/messenger-platform/messenger-profile/target-audience>`_
    """
    url = MESSENGER_PROFILE_URL.format(access_token=PAGE_ACCESS_TOKEN)
    payload = {"target_audience": {}}
    payload["target_audience"]["audience_type"] = audience_type
    if audience_type in ['custom', 'none']:
        payload["target_audience"]["countries"] = countries
    data = json.dumps(payload)
    status = requests.post(url, headers=HEADER, data=data)
    return status
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_chat_extension_home_url(
     url, webview_share_button="hide", in_test=True):
    """ Sets the url field enabling a Chat Extension in the composer \
    drawer in Messenger.

    :param str url: The URL to be invoked from drawer.
    :param str webview_share_button: Controls whether the share button in \
    the webview is enabled. (Set to "show" or "hide")
    :param bool in_test: Controls whether public users (not assigned to the \
    bot or its Facebook page) can see the Chat Extension.
    :return: `Response object <http://docs.python-requests.org/en/\
    master/api/#requests.Response>`_
    :facebook docs: `/home-url <https://developers.facebook.\
    com/docs/messenger-platform/messenger-profile/home-url>`_
    """
    url = MESSENGER_PROFILE_URL.format(access_token=PAGE_ACCESS_TOKEN)
    payload = {"home_url": {}}
    payload["home_url"]["url"] = url
    payload["home_url"]["webview_height_ratio"] = "tall"
    payload["home_url"]["webview_share_button"] = webview_share_button
    payload["home_url"]["in_test"] = in_test
    data = json.dumps(payload)
    status = requests.post(url, headers=HEADER, data=data)
    return status


#############################################
#           Send Api Functions              #
#############################################

# Send API Sender Actions
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_sender_action(fbid, sender_action):
    """ Displays/Hides the typing gif or shows mark seen on
    facebook chat with user.

    :usage:

        >>> # Set the user you want to show action
        >>> fbid = "<user page scoped id>"
        >>> # To show the typing animation
        >>> fbbotw.post_sender_action(
                fbid=fbid, sender_action="typing_on"
            )
        >>> # To stop typing (Stops automatically after 20s)
        >>> fbbotw.post_sender_action(
                fbid=fbid, sender_action="typing_off"
            )
        >>> # To mark as seen
        >>> fbbotw.post_sender_action(
                fbid=fbid, sender_action="mark_seen"
            )
    :param str fbid: User id to display action.
    :param str sender_action: `typing_off/typing_on/mark_seen`.
    :return: `Response object <http://docs.python-requests.org/en/\
    master/api/#requests.Response>`_
    :facebook docs: `/sender-actions <https://developers.facebook.\
    com/docs/messenger-platform/send-api-reference/sender-actions>`_
    """
    url = MESSAGES_URL.format(access_token=PAGE_ACCESS_TOKEN)
    payload = {}
    payload['recipient'] = {'id': fbid}
    payload['sender_action'] = sender_action
    data = json.dumps(payload)
    status = requests.post(url, headers=HEADER, data=data)
    return status


# Send API Content Type
项目:fbbotw    作者:JoabMendes    | 项目源码 | 文件源码
def post_text_list(fbid, messages=[]):
    """ Sends a serie of messages from a list of texts. The
    messages will be sent in the same order as the list items.

    :usage:

        >>> # Set the user fbid and the list of texts to send.
        >>> fbid = "<user page scoped id>"
        >>> texts = [
                "Hi, Todays forecast is:",
                "Morning: Sunny - 27C",
                "Afternoon: Sunny - 25C",
                "Night: Cloudy - 18C"
            ]
        >>> response = fbbotw.post_text_list(
                fbid=fbid,
                messages=texts
            )
    :param str fbid: User id to send the text list.
    :param list messages: A list of messages to be sent.
    :return: A list of `Response objects <http://docs.python-\
    requests.org/en/master/api/#requests.Response>`_\
    for every message sent.
    """
    responses = []
    for msg in messages:
        responses.append(post_text_message(fbid=fbid, message=msg))
    return responses