本文整理汇总了Python中bottle.request.headers方法的典型用法代码示例。如果您正苦于以下问题:Python request.headers方法的具体用法?Python request.headers怎么用?Python request.headers使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bottle.request
的用法示例。
在下文中一共展示了request.headers方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: key_auth
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import headers [as 别名]
def key_auth(name=""):
"""Authenticates a API key."""
if 'secret' in request.forms:
secret = request.forms["secret"]
elif 'X-Lokun-Secret' in request.headers:
secret = request.headers["X-Lokun-Secret"]
else:
abort(401, "Must include a secret")
try:
return model.APIKey.auth(secret, name=name)
except ValueError:
log("Not accepted: " + repr(request.forms['secret']))
abort(403, "Secret not accepted")
# ------------
# /users/
# ------------
示例2: get_next_page
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import headers [as 别名]
def get_next_page(r):
link = r.headers.get('Link', None)
if not link:
return None
n1 = link.find('rel=\"next\"')
if n1 < 0:
return None
n2 = link.rfind('<', 0, n1)
if n2 < 0:
return None
n2 += 1
n3 = link.find('>;', n2)
return link[n2:n3]
示例3: __call__
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import headers [as 别名]
def __call__(self, callback):
def wrapper(*args, **kwargs):
if not is_local_request():
self._logger.info('Dropping request with bad Host header.')
abort(httplib.UNAUTHORIZED,
'Unauthorized, received request from non-local Host.')
return
if not self.is_request_authenticated():
self._logger.info('Dropping request with bad HMAC.')
abort(httplib.UNAUTHORIZED, 'Unauthorized, received bad HMAC.')
return
body = callback(*args, **kwargs)
self.sign_response_headers(response.headers, body)
return body
return wrapper
示例4: _getBson
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import headers [as 别名]
def _getBson(self):
''' If the ``Content-Type`` header is ``application/bson``, this
property holds the parsed content of the request body. Only requests
smaller than :attr:`MEMFILE_MAX` are processed to avoid memory
exhaustion. '''
max_size = BII_MAX_MEMORY_PER_REQUEST
if request.headers['Content-Type'] == 'application/bson':
if 0 < request.content_length < max_size:
return decode_bson(request.body.read(max_size))
else:
logger.error("Max size of bson for request: %i" % request.content_length)
# DO NOT REMOVE: BODY NEEDS TO BE READED BEFORE RAISE, IT SEEMS LIKE A BOTTLE BUG
request.body.read(0)
raise BSONBottlePluginException("Max request size overtaken")
else:
raise BSONBottlePluginException("Not Bson request in a method with bson_param specified")
return None
示例5: getuser
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import headers [as 别名]
def getuser(name):
"""This is POST only because GET shows passwords in url.
TODO: Move key to headers"""
user = auth(name)
return dict(user)
示例6: post_method
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import headers [as 别名]
def post_method(data=None, content_type=None):
if not data:
data = request.body.read().decode('utf-8')
if not content_type:
content_type = request.content_type
if 'x-amz-sns-message-type' not in request.headers.keys():
raise Exception('missing headers')
if request.headers['x-amz-sns-message-type'] != 'SubscriptionConfirmation':
return
url = json.loads(data)['SubscribeURL']
requests.get(url)
return
示例7: session
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import headers [as 别名]
def session(callback):
cookie_name = 'session'
serializer = URLSafeSerializer(conf['SECRET'])
def inner(*args, **kwargs):
data_raw = data = request.get_cookie(cookie_name)
if data_raw:
try:
data = serializer.loads(data_raw)
except (BadSignature, BadData):
data = None
if data:
conf['USER'] = data['username']
request.session = data or {}
try:
return callback(*args, **kwargs)
finally:
if request.session:
save(request.session)
elif not data_raw:
pass
else:
response.delete_cookie(cookie_name)
def save(session):
cookie_opts = {
# keep session for 3 days
'max_age': 3600 * 24 * 3,
# for security
'httponly': True,
'secure': request.headers.get('X-Forwarded-Proto') == 'https',
}
data = serializer.dumps(session)
response.set_cookie(cookie_name, data, **cookie_opts)
return inner
示例8: nginx
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import headers [as 别名]
def nginx():
h = request.headers
try:
login, pw = h['Auth-User'], h['Auth-Pass']
protocol = h['Auth-Protocol']
except KeyError as e:
return abort(400, repr(e))
if login in conf['IMAP_OFF']:
response.set_header('Auth-Status', 'Disabled')
response.set_header('Auth-Wait', 3)
return ''
port = {'imap': '143', 'smtp': '25'}[protocol]
try:
local.connect(login, pw)
response.set_header('Auth-Status', 'OK')
response.set_header('Auth-Server', '127.0.0.1')
response.set_header('Auth-Port', port)
except imap.Error as e:
response.set_header('Auth-Status', str(e))
response.set_header('Auth-Wait', 3)
return ''
示例9: get_commits
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import headers [as 别名]
def get_commits(url, token):
headers = {
"Authorization": "token " + token,
"User-Agent": "InfraBox"
}
s = requests.Session()
retries = Retry(total=5,
backoff_factor=0.1,
status_forcelist=[500, 502, 503, 504])
s.mount('http://', HTTPAdapter(max_retries=retries))
# TODO(ib-steffen): allow custom ca bundles
r = requests.get(url + '?per_page=100', headers=headers, verify=False)
result = []
result.extend(r.json())
p = get_next_page(r)
while p:
r = requests.get(p, headers=headers, verify=False)
p = get_next_page(r)
result.extend(r.json())
return result
示例10: trigger_build
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import headers [as 别名]
def trigger_build(conn):
headers = dict(request.headers)
if 'X-Github-Event' not in headers:
return res(400, "X-Github-Event not set")
if 'X-Hub-Signature' not in headers:
return res(400, "X-Hub-Signature not set")
event = headers['X-Github-Event']
sig = headers['X-Hub-Signature']
#pylint: disable=no-member
body = request.body.read()
secret = get_env('INFRABOX_GITHUB_WEBHOOK_SECRET')
signed = sign_blob(secret, body)
if signed != sig:
return res(400, "X-Hub-Signature does not match blob signature")
trigger = Trigger(conn)
if event == 'push':
return trigger.handle_push(request.json)
elif event == 'pull_request':
return trigger.handle_pull_request(request.json)
return res(200, "OK")
示例11: is_request_authenticated
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import headers [as 别名]
def is_request_authenticated(self):
return self._hmachelper.is_request_authenticated(request.headers,
request.method,
request.path,
request.body.read())
示例12: sign_response_headers
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import headers [as 别名]
def sign_response_headers(self, headers, body):
self._hmachelper.sign_response_headers(headers, body)
示例13: is_local_request
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import headers [as 别名]
def is_local_request():
host = urlparse('http://' + request.headers['host']).hostname
return host == '127.0.0.1' or host == 'localhost'
示例14: travis
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import headers [as 别名]
def travis():
logger = g.logger.getChild('travis')
info = json.loads(request.forms.payload)
lazy_debug(logger, lambda: 'info: {}'.format(utils.remove_url_keys_from_json(info)))
try: state, repo_label = find_state(info['commit'])
except ValueError:
lazy_debug(logger, lambda: 'Invalid commit ID from Travis: {}'.format(info['commit']))
return 'OK'
lazy_debug(logger, lambda: 'state: {}, {}'.format(state, state.build_res_summary()))
if 'travis' not in state.build_res:
lazy_debug(logger, lambda: 'travis is not a monitored target for {}'.format(state))
return 'OK'
repo_cfg = g.repo_cfgs[repo_label]
token = repo_cfg['travis']['token']
auth_header = request.headers['Authorization']
code = hashlib.sha256(('{}/{}{}'.format(state.owner, state.name, token)).encode('utf-8')).hexdigest()
if auth_header != code:
# this isn't necessarily an error, e.g. maybe someone is
# fabricating travis notifications to try to trick Homu, but,
# I imagine that this will most often occur because a repo is
# misconfigured.
logger.warn('authorization failed for {}, maybe the repo has the wrong travis token? ' \
'header = {}, computed = {}'
.format(state, auth_header, code))
abort(400, 'Authorization failed')
succ = info['result'] == 0
report_build_res(succ, info['build_url'], 'travis', state, logger, repo_cfg)
return 'OK'
示例15: instructions
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import headers [as 别名]
def instructions(keys):
authenticated = False
if "Cookie" in request.headers:
cookies = request.headers["Cookie"].split(";")
for c in cookies:
if c.strip().startswith("apikey="):
authenticated = checkAPIkey(c.strip()[7:])
if "token" in keys and authenticated:
token = keys.get("token")
parameters = {
"method":"auth.getSession",
"token":token,
"api_key":get_settings("LASTFM_API_KEY")
}
response = urllib.request.urlopen("http://ws.audioscrobbler.com/2.0/?" + lfmbuild(parameters))
xml = response.read()
data = ET.fromstring(xml)
if data.attrib.get("status") == "ok":
username = data.find("session").find("name").text
sessionkey = data.find("session").find("key").text
update_settings("settings/settings.ini",{"LASTFM_API_SK":sessionkey,"LASTFM_USERNAME":username},create_new=True)
return "/proxy"
else:
key,secret,sessionkey,name = get_settings("LASTFM_API_KEY","LASTFM_API_SECRET","LASTFM_API_SK","LASTFM_USERNAME")
if key is None:
lastfm = "<td>No Last.fm key provided</td>"
elif secret is None:
lastfm = "<td>No Last.fm secret provided</td>"
elif sessionkey is None and authenticated:
url = "http://www.last.fm/api/auth/?api_key=" + key + "&cb="
lastfm = "<td class='button'><a id='lastfmlink' href='" + url + "'><div>Connect</div></a></td>"
elif sessionkey is None:
lastfm = "<td>Not active</td>"
else:
lastfm = "<td>Account: " + name + "</td>"
return {"KEY_STATUS_LASTFM":lastfm},[]