2017-08-15 06:07:24 +00:00
|
|
|
"""Misc common utilities.
|
|
|
|
"""
|
|
|
|
import logging
|
|
|
|
|
2017-08-23 15:14:51 +00:00
|
|
|
from oauth_dropins.webutil import util
|
2017-08-15 06:07:24 +00:00
|
|
|
import requests
|
2017-08-15 14:39:22 +00:00
|
|
|
from webob import exc
|
|
|
|
|
2017-09-03 19:54:10 +00:00
|
|
|
DOMAIN_RE = r'([^/]+\.[^/]+)'
|
|
|
|
ACCT_RE = r'(?:acct:)?([^@]+)@' + DOMAIN_RE
|
2017-08-15 06:07:24 +00:00
|
|
|
HEADERS = {
|
2017-08-19 14:41:25 +00:00
|
|
|
'User-Agent': 'Bridgy Fed (https://fed.brid.gy/)',
|
2017-08-15 06:07:24 +00:00
|
|
|
}
|
2017-08-23 15:14:51 +00:00
|
|
|
ATOM_CONTENT_TYPE = 'application/atom+xml'
|
|
|
|
MAGIC_ENVELOPE_CONTENT_TYPE = 'application/magic-envelope+xml'
|
2017-09-02 03:49:00 +00:00
|
|
|
XML_UTF8 = "<?xml version='1.0' encoding='UTF-8'?>\n"
|
2017-08-15 06:07:24 +00:00
|
|
|
|
|
|
|
def requests_get(url, **kwargs):
|
2017-08-23 15:14:51 +00:00
|
|
|
return _requests_fn(util.requests_get, url, **kwargs)
|
2017-08-15 06:07:24 +00:00
|
|
|
|
|
|
|
|
2017-08-15 14:39:22 +00:00
|
|
|
def requests_post(url, **kwargs):
|
2017-08-23 15:14:51 +00:00
|
|
|
return _requests_fn(util.requests_post, url, **kwargs)
|
2017-08-15 06:07:24 +00:00
|
|
|
|
|
|
|
|
2017-09-02 03:49:00 +00:00
|
|
|
def _requests_fn(fn, url, parse_json=False, log=False, **kwargs):
|
2017-08-15 14:39:22 +00:00
|
|
|
"""Wraps requests.* and adds raise_for_status() and User-Agent."""
|
|
|
|
kwargs.setdefault('headers', {}).update(HEADERS)
|
2017-08-23 15:14:51 +00:00
|
|
|
|
2017-08-15 14:39:22 +00:00
|
|
|
resp = fn(url, **kwargs)
|
2017-09-02 03:49:00 +00:00
|
|
|
if log:
|
|
|
|
logging.info('Got %s\n headers:%s\n%s', resp.status_code, resp.headers,
|
|
|
|
resp.text)
|
2017-08-15 14:39:22 +00:00
|
|
|
resp.raise_for_status()
|
|
|
|
|
2017-08-23 15:14:51 +00:00
|
|
|
if parse_json:
|
2017-08-15 14:39:22 +00:00
|
|
|
try:
|
|
|
|
return resp.json()
|
|
|
|
except ValueError:
|
|
|
|
msg = "Couldn't parse response as JSON"
|
|
|
|
logging.error(msg, exc_info=True)
|
2017-08-23 15:14:51 +00:00
|
|
|
raise exc.HTTPBadRequest(msg)
|
2017-08-15 14:39:22 +00:00
|
|
|
|
|
|
|
return resp
|
2017-08-23 15:14:51 +00:00
|
|
|
|
|
|
|
|
|
|
|
def error(handler, msg, status=400):
|
|
|
|
logging.info(msg)
|
|
|
|
handler.abort(status, msg)
|