本文整理汇总了Python中webapp2.abort函数的典型用法代码示例。如果您正苦于以下问题:Python abort函数的具体用法?Python abort怎么用?Python abort使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了abort函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: custom_dispatcher
def custom_dispatcher(router, request, response):
route, args, kwargs = rv = router.match(request)
request.route, request.route_args, request.route_kwargs = rv
handler = route.handler
if isinstance(handler, basestring):
handler, args, kwargs = parse_handler_template(request, handler, args, kwargs)
# debug logging
# logging.info('handler is %s' % handler)
# logging.info(request.route_args)
# logging.info(request.route_kwargs)
# for x in request.params:
# logging.info('Param is %s' % x)
# logging.info(args)
# logging.info(kwargs)
try:
handler = webapp2.import_string(handler)
# Module, Controller, Action 文字列格納
handler.adapted_handler_spec = kwargs
# jinjaテンプレート定義
handler.JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(
spy_setting.MODULES_DIR + "/" + kwargs["module"] + "/views/templates/" + kwargs["controller"]
),
extensions=["jinja2.ext.autoescape"],
)
router.handlers[handler] = handler
except webapp2.ImportStringError:
webapp2.abort(404)
return router.adapt(handler)(request, response)
开发者ID:potch8228,项目名称:spyhopReader,代码行数:32,代码来源:router.py
示例2: get
def get(self):
try:
transaction_key = int(self.request.GET[self.TRANSACTION_KEY])
if not transaction_key:
raise ValueError
except Exception, e:
webapp2.abort(400, "{} missing. Can't connect to user".format(self.TRANSACTION_KEY))
开发者ID:jerrico,项目名称:backend,代码行数:7,代码来源:main.py
示例3: _handle_request
def _handle_request(self):
schema = self._get_schema()
pretty = self._get_pretty()
if not schema:
webapp2.abort(500, detail='GraphQL Schema is missing.')
query, operation_name, variables, pretty_override = self._get_grapl_params()
pretty = pretty if not pretty_override else pretty_override
result = schema.execute(query,
operation_name=operation_name,
variable_values=variables,
context_value=self._get_context(),
root_value=self._get_root_value(),
middleware=self._get_middleware())
response = {}
if result.errors:
response['errors'] = [self.__format_error(e) for e in result.errors]
logging.warn("Request had errors: %s", response)
self._handle_graphql_errors(result.errors)
if result.invalid:
logging.error("GraphQL request is invalid: %s", response)
return self.failed_response(400, response, pretty=pretty)
response['data'] = result.data
return self.successful_response(response, pretty=pretty)
开发者ID:graphql-python,项目名称:graphene-gae,代码行数:29,代码来源:__init__.py
示例4: get
def get(self, id=0):
try:
# Get photo
photo = get_flickr_json('photo',
flickr.photos.getInfo(photo_id=id, format='json',
nojsoncallback=1))
# Check photosets
contexts = get_flickr_json('set',
flickr.photos.getAllContexts(photo_id=id, format='json',
nojsoncallback=1))
# Photo should only be in one set, check ID
id = int(contexts[0].get('id'))
if id == settings.PHOTOSET_ID:
photo['archive'] = False
elif id == settings.PHOTOSET_ARCHIVE_ID:
photo['archive'] = True
else:
raise
except:
# Go 404 if not found, e.g. photo not found
webapp2.abort(404)
# Write as JSON
self.response.headers['Content-Type'] = "application/json; charset=utf-8"
self.response.out.write(json.dumps(photo))
开发者ID:marchibbins,项目名称:college-garth,代码行数:28,代码来源:main.py
示例5: get
def get(self):
# データブックの名前を取得
databook_name = get_databook_name(self.request.get('db'))
# 記事のタイトルをチェック
req_title = self.request.get('title').strip()
if not req_title:
no_article = 1
else:
no_article = 0
# 記事を検索(タイトルで1件だけ)
if no_article == 0:
articles_query = Article.query(Article.title == req_title, ancestor=databook_key(databook_name)).order(-Article.date)
articles = articles_query.fetch(1)
if len(articles) < 1:
no_article = 1
else:
article = articles[0]
# # 記事が存在しなければダミーの空データを作成
# if no_article == 1:
# article = Article(parent=databook_key(databook_name))
# article.source = ''
# 記事が存在しなければ 404 Not Found エラーにする
if no_article == 1:
webapp2.abort(404)
return
# 実行ページのテンプレートに記事データを埋め込んで表示
template = jinja_environment.get_template(runpage_html)
self.response.out.write(template.render(databook_name=databook_name,
article=article))
开发者ID:Hamayama,项目名称:databook,代码行数:34,代码来源:databook.py
示例6: _make_request
def _make_request(self, url, method, headers=None, body=None):
"""Helper for making API requests, including retries. On success,
returns the content of the response. On failure, throws HTTPException.
"""
if not headers:
headers = self._headers
attempt = 0
while attempt < _RETRIES:
attempt += 1
logging.debug('%s: %s', method, url)
response, content = self._http.request(url, method=method,
headers=headers,
body=body)
# This is pretty dirty. But PUT entry-creation reqs give a status
# of 201, and basically all 20x statuses are successes, so...
if not response['status'].startswith('20'):
# Fail. Retry.
logging.debug(response)
logging.debug(content)
continue
return content
# If we got to here, then the request failed repeatedly.
webapp2.abort(int(response['status']), detail=content)
开发者ID:adam-p,项目名称:danforth-east,代码行数:30,代码来源:googledata.py
示例7: post
def post(self):
username = self.authenticate()
json_object = json.loads(self.request.body)
self.validate_json_fields(["game_id", "message"], json_object)
logging.debug("Extracting game from model...")
game_id = json_object["game_id"]
game = game_repo.extract_game(game_id)
if not game:
error_message = "Could not find game for game_id <{}>".format(game_id)
logging.warn(error_message)
webapp2.abort(404, detail=error_message)
else:
logging.debug("Game id <{}> found".format(game_id))
message = json_object["message"]
if message not in ("status", "join", "move"):
logging.warn("Invalid message type <{}>".format(message))
webapp2.abort(422, detail="Invalid message type <{}>".format(message))
content = handle_client_message(username, game, json_object)
self.response.content_type = "application/json"
self.response.write(json.dumps(content))
开发者ID:supermitch,项目名称:mech-ai,代码行数:25,代码来源:server.py
示例8: get
def get(self, proceeding=DEFAULT_PROCEEDING, comment_id=None):
if comment_id:
self.response.cache_control = 'public'
self.response.cache_control.max_age = 10*60
comment = datastore.Comment.getComment(proceeding, comment_id)
if not comment:
webapp2.abort(404)
else:
comment = datastore.Comment.getRandom(proceeding)
twitter_text, long_summary = comment_text_summary(comment)
start = time.time()
args = {
'comment': comment,
'comment_text': None,
'comment_link': permalinkForComment(comment),
'twitter_text': twitter_text,
'long_summary': long_summary,
}
if comment.DocText:
args['comment_text'] = comment.DocText.replace('\n\n', '</p>\n<p>').replace('\n', '');
self.render_response("index.html", **args)
开发者ID:jjhuff,项目名称:fcc-comments,代码行数:25,代码来源:main.py
示例9: authorize_new_user
def authorize_new_user(request, user):
"""Creates a new member with the data in the reqeust.
"""
logging.info('authorize_user')
logging.info(request.params.items())
new_user = config.validate_obj_against_fields(request.POST,
config.AUTHORIZED_FIELDS)
if not new_user:
# This causes the request processing to stop
webapp2.abort(400, detail='invalid input')
# Check if this user (i.e., email) is already authorized
# NOTE: We're putting "" around the second %s because otherwise the query
# gives an error.
querystring = '%s=="%s"' % (config.AUTHORIZED_FIELDS.email.name,
request.POST.get(config.AUTHORIZED_FIELDS.email.name))
existing_user = _get_single_list_entry(querystring,
config.AUTHORIZED_SPREADSHEET_KEY,
config.AUTHORIZED_WORKSHEET_KEY)
if existing_user:
# This causes the request processing to stop
webapp2.abort(400, detail='user email address already authorized')
# Set the GUID field
new_user[config.AUTHORIZED_FIELDS.id.name] = str(uuid.uuid4())
# Set the timestamps
new_user[config.AUTHORIZED_FIELDS.created.name] = utils.current_datetime()
new_user[config.AUTHORIZED_FIELDS.created_by.name] = user.email()
_add_new_row(new_user,
config.AUTHORIZED_SPREADSHEET_KEY,
config.AUTHORIZED_WORKSHEET_KEY)
开发者ID:adam-p,项目名称:danforth-east,代码行数:35,代码来源:gapps.py
示例10: post
def post(self):
artwork_json = json.loads(self.request.get("json"))
publish_date = datetime.datetime.utcfromtimestamp(artwork_json["publishDate"] / 1000).date()
if FeaturedArtwork.all().filter("publish_date=", publish_date).get() != None:
webapp2.abort(409, message="Artwork already exists for this date.")
crop_tuple = tuple(float(x) for x in json.loads(self.request.get("crop")))
new_image_url, new_thumb_url = backroomarthelper.maybe_process_image(
artwork_json["imageUri"],
crop_tuple,
publish_date.strftime("%Y%m%d") + " " + artwork_json["title"] + " " + artwork_json["byline"],
)
if not new_thumb_url and "thumbUri" in artwork_json:
new_thumb_url = artwork_json["thumbUri"]
new_artwork = FeaturedArtwork(
title=artwork_json["title"],
byline=artwork_json["byline"],
attribution=artwork_json["attribution"] if "attribution" in artwork_json else None,
image_url=new_image_url,
thumb_url=new_thumb_url,
details_url=artwork_json["detailsUri"],
publish_date=publish_date,
)
new_artwork.save()
self.response.set_status(200)
开发者ID:romannurik,项目名称:muzei,代码行数:28,代码来源:backroom.py
示例11: get
def get(self, key):
game_key = ndb.Key(urlsafe=key)
user = users.get_current_user()
if not game_key:
webapp2.abort(404, 'Game not found')
game = game_key.get()
characters = models.Character.query(ancestor=game_key).fetch(limit=100)
player_characters = [c for c in characters if c.player == user]
other_characters = [c for c in characters if not c.player == user]
player_character = None
if player_characters:
player_character = player_characters[0]
game_owner = user in game.admins
template_values = {
"title": game.title,
"game": game,
"your_character": player_character,
"game_owner": game_owner,
"other_characters": other_characters,
}
template = templates.get_template('game.html')
self.response.write(template.render(template_values))
开发者ID:rrees,项目名称:at-light-speed,代码行数:30,代码来源:pages.py
示例12: build_manifest
def build_manifest(appname):
"""Creates a manifest for the app."""
try:
data = app_data.APPS[appname]
except KeyError:
webapp2.abort(404, explanation='No such app: %s' % appname)
# Create the manifest dictionary, tailoring it based on |data|.
# Insert the items in the order they are documented in the Manifest spec.
manifest = collections.OrderedDict()
if 'web_stuff' in data and data['web_stuff']:
manifest['name'] = app_data.DEFAULT_NAME
manifest['short_name'] = app_data.DEFAULT_SHORT_NAME
manifest['icons'] = app_data.DEFAULT_ICONS
manifest['display'] = app_data.DEFAULT_DISPLAY
manifest['start_url'] = app_data.DEFAULT_START_URL
FIELDS = ('icons', 'display', 'related_applications',
'prefer_related_applications')
for field in FIELDS:
if field in data:
if data[field] is not None:
manifest[field] = data[field]
elif field in manifest:
del manifest[field]
return json.dumps(manifest, indent=2, separators=(',', ': ')) + '\n'
开发者ID:dominickng,项目名称:killer-marmot,代码行数:26,代码来源:main.py
示例13: get
def get(self, entries="4"):
template = jinja_environment.get_template("recipe-box.html")
headers.cors(self.response)
last_60_days = date.today() - timedelta(days=60)
query = {
"tag" : "tone/recipes",
"show-fields" : "headline,thumbnail",
"page-size" : 50,
"from-date" : last_60_days.isoformat(),
}
content = content_api.search(query)
if not content:
webapp2.abort(500, "Failed to read recipes list")
content_data = json.loads(content)
recipes = content_data.get("response", {}).get("results", [])
recipes = [r for r in recipes if "thumbnail" in r.get("fields", {})]
random.shuffle(recipes)
data = {
"recipes" : recipes[0:int(entries)],
}
self.response.out.write(template.render(data))
开发者ID:guardian,项目名称:gdn-food,代码行数:31,代码来源:components.py
示例14: with_registry_name
def with_registry_name(self, registry_name, *args, **kwargs):
registry = Registry.get_by_name(registry_name)
logging.info(str(registry))
if not registry:
logging.info(str(registry))
webapp2.abort(404)
return f(self, registry, *args, **kwargs)
开发者ID:tobiasljohnson,项目名称:registry,代码行数:7,代码来源:main.py
示例15: get
def get(self, report_id):
try:
report = ndb.Key(urlsafe=report_id).get()
except:
webapp2.abort(404)
self.response.write(report.to_html())
开发者ID:timw6n,项目名称:mm-cloud-reports,代码行数:7,代码来源:main.py
示例16: get
def get(self, path="film"):
logging.info(path)
path_mapping = immutable.make_dict({
'film': container.for_id('6d84cd8d-d159-4e9a-ba2f-8852528d2d03'),
'uk/opinion/v1': container.for_id('uk/commentisfree/regular-stories'),
'film/v1': ds.FilmTodayLatestDataSource(mr.client),
})
if not path in path_mapping.keys():
webapp2.abort(404, "Path {0} not mapped to a datasource".format(path))
return
stories_data_source = path_mapping[path]
data_sources = {'stories': stories_data_source}
priority_list = [('stories', 1)]
template_data = {}
retrieved_data = handlers.EmailTemplate.fetch_all(data_sources)
trail_block = deduplication.build_unique_trailblocks(retrieved_data,priority_list)
stories = trail_block.get('stories')
headlines = [read_headline(s) for s in stories]
if headlines:
headline = headlines[0]
template_data['headline'] = headline
template = handlers.jinja_environment.get_template('headline.html')
self.response.out.write(template.render(template_data))
开发者ID:guardian,项目名称:gu-email-renderer,代码行数:29,代码来源:headlines.py
示例17: post
def post(self):
data = json.loads(self.request.body)
if "desc" not in data.keys(): webapp2.abort(400)
new = Todo()
new.desc = data["desc"]
new.put()
self.response.out.write(json.dumps({"message":"Okay, task registered. Time to work, huh?"}))
开发者ID:clenimar,项目名称:querocomergostoso,代码行数:7,代码来源:metadata.py
示例18: post
def post(self):
"""Serve the form page.
"""
logging.info('PaypalIpnHandler.POST')
logging.info('headers: %s', self.request.headers.items())
logging.info('params: %s', self.request.params.items())
# First check with Paypal to see if this notification is legit
validation_url = config.PAYPAL_IPN_VALIDATION_URL % (self.request.body,)
http = httplib2.Http()
resp, body = http.request(validation_url, method='POST')
if resp.status != 200 or body != 'VERIFIED':
# NOT LEGIT
logging.warning('invalid IPN request')
logging.warning('%d; %s', resp.status, body)
webapp2.abort(403)
# Check if this actually represents a payment
if self.request.params.get('payment_status') != 'Completed':
# Not a completed payment, but some intermediate event. We don't
# do anything with these.
logging.info('IPN with status: %s',
self.request.params.get('payment_status'))
return # 200
# Check if the payment values are valid
if not self._paypal_txn_values_okay():
# Alert our admins about this
subject = 'ALERT: bad values in PayPal transaction'
body = '''
We received a valid PayPal IPN transaction that contained incorrect or
unexpected values. Specifically, either the recipient email address doesn't
match ours (should be: %s), the value of the transaction was insufficient
(should be: %s), or it was in an incorrect currency (should be: %s).
Here are the transaction values:
%s
Current URL:
%s
[This email was sent automatically.]
''' % (config.PAYPAL_TXN_receiver_email,
config.PAYPAL_TXN_mc_gross_FLOAT,
config.PAYPAL_TXN_mc_currency_SET,
pprint.pformat(self.request.params.items()),
self.request.host_url)
mail.send_mail_to_admins(config.MASTER_EMAIL_SEND_ADDRESS,
subject,
body)
logging.info('IPN had bad values')
return # 200
# Launch a task to actually create or renew the member.
# We'll pass the Paypal params straight through.
taskqueue.add(url='/self-serve/process-member-worker',
params=self.request.params)
开发者ID:adam-p,项目名称:danforth-east,代码行数:60,代码来源:self-serve.py
示例19: checkPerm
def checkPerm(self):
user = models.Author.getUser()
if user is None or not user.isAdmin():
webapp2.abort(403)
return user
开发者ID:MattDiesel,项目名称:pad.mattdiesel.co.uk,代码行数:7,代码来源:main.py
示例20: list_game_by_username_and_id
def list_game_by_username_and_id(username, id):
"""
Return game results as a dictionary, for given query params.
Common functionality to list games by username & id. Both can be None.
"""
if id:
logging.debug("in here")
results = [game_repo.find_by_id(id)]
elif username:
results = game_repo.find_by_username(username)
else:
message = "Tried to list games without username or ID"
webapp2.abort(404, detail=message)
results = results if results else []
return {
"results": [
{
"id": game_model.key.id(),
"name": game_model.name,
"players": game_model.players,
"map_name": game_model.map_name,
"status": game_model.status,
"created": game_model.created.isoformat(),
"transactions": json.loads(game_model.transactions),
}
for game_model in results
]
}
开发者ID:supermitch,项目名称:mech-ai,代码行数:30,代码来源:server.py
注:本文中的webapp2.abort函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论