def enable_cors(self):
'''Enables Cross Origin Resource Sharing.
This makes sure the necessary headers are set so that this
web application's routes can be accessed from other origins.
:rtype: :class:`WebBuilder`
'''
def access_control_headers():
bottle.response.headers['Access-Control-Allow-Origin'] = '*'
bottle.response.headers['Access-Control-Allow-Methods'] = \
'GET, POST, PUT, DELETE, OPTIONS'
bottle.response.headers['Access-Control-Allow-Headers'] = \
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
def options_response(res):
if bottle.request.method == 'OPTIONS':
new_res = bottle.HTTPResponse()
new_res.headers['Access-Control-Allow-Origin'] = '*'
new_res.headers['Access-Control-Allow-Methods'] = \
bottle.request.headers.get(
'Access-Control-Request-Method', '')
new_res.headers['Access-Control-Allow-Headers'] = \
bottle.request.headers.get(
'Access-Control-Request-Headers', '')
return new_res
res.headers['Allow'] += ', OPTIONS'
return bottle.request.app.default_error_handler(res)
self.app.add_hook('after_request', access_control_headers)
self.app.error_handler[int(405)] = options_response
return self
python类response()的实例源码
def apply(self, callback, route):
if not route.config.get('json', False):
return callback
def _(*args, **kwargs):
bottle.response.content_type = 'application/json'
return json.dumps(callback(*args, **kwargs), indent=2)
return _
def followup(dry_run):
if dry_run:
print("DRY RUN -- Not sending actual emails")
config['DEBUG'] = True
"Run after changing the question schema; sends out email updates. Recommended at most once per month."
emails = []
usrs = []
for user in r.table('users').run(conn()):
if 'subscribed' not in user or user['subscribed'] == False:
# Ignore anonymous or unsubscribed users
continue
# Get email for email/xenforo accounts
usrs.append(user)
emails.append(user['email'] if 'email' in user else user['identity'])
print("Sending emails to the following %s users", (len(emails), emails))
desc = sys.stdin.read()
for user in usrs:
users.mail(user, 'Questions have been updated',
"""You are receiving this email because the questions have been updated. Please consider logging in and updating your response.<br>
<br>
Update notes:<br>
%s<br>
""" % desc.replace('\n', '<br>'),
"""You are receiving this email because the questions have been updated. Please conisder logging in and updating your response\n
\n
Update notes:%s\n""" % desc, use_flash = False)
def verify_recaptcha_form():
if config['DEBUG']:
return True
captcha_rs = request.forms.get('g-recaptcha-response')
req = requests.get('https://www.google.com/recaptcha/api/siteverify',
params = {
'secret': config['RECAPTCHA_SECRET_KEY'],
'response': request.forms.get('g-recaptcha-response'),
'remoteip': request.remote_addr
}, verify=True).json()
return req.get("success", False)
def get_countdowns() -> str:
"""Returns a json response of countdowns."""
return json_api.get_countdowns(response)
def get_app(self):
'''Eliminate the builder by producing a new Bottle application.
This should be the final call in your method chain. It uses all
of the built up options to create a new Bottle application.
:rtype: :class:`bottle.Bottle`
'''
if self.config is None:
# If the user never sets a config instance, then just create
# a default.
self.config = Config()
if self.mount_prefix is None:
self.mount_prefix = self.config.config.get('url_prefix')
self.inject('config', lambda: self.config)
self.inject('kvlclient', lambda: self.config.kvlclient)
self.inject('store', lambda: self.config.store)
self.inject('label_store', lambda: self.config.label_store)
self.inject('tags', lambda: self.config.tags)
self.inject('search_engines', lambda: self.search_engines)
self.inject('filters', lambda: self.filters)
self.inject('request', lambda: bottle.request)
self.inject('response', lambda: bottle.response)
# DEPRECATED. Remove. ---AG
self.inject('visid_to_dbid', lambda: self.visid_to_dbid)
self.inject('dbid_to_visid', lambda: self.dbid_to_visid)
# Also DEPRECATED.
self.inject('label_hooks', lambda: [])
# Load routes defined in entry points.
for extroute in self.config.config.get('external_routes', []):
mod, fun_name = extroute.split(':')
logger.info('Loading external route: %s', extroute)
fun = getattr(__import__(mod, fromlist=[fun_name]), fun_name)
self.add_routes(fun())
# This adds the `json=True` feature on routes, which always coerces
# the output to JSON. Bottle, by default, only permits dictionaries
# to be JSON, which is the correct behavior. (Because returning JSON
# arrays is a hazard.)
#
# So we should fix the routes and then remove this. ---AG
self.app.install(JsonPlugin())
# Throw away the app and return it. Because this is elimination!
app = self.app
self.app = None
if self.mount_prefix is not None:
root = bottle.Bottle()
root.mount(self.mount_prefix, app)
return root
else:
return app