当前位置: 首页>>代码示例>>Python>>正文


Python webapp2.abort函数代码示例

本文整理汇总了Python中webapp2.abort函数的典型用法代码示例。如果您正苦于以下问题:Python abort函数的具体用法?Python abort怎么用?Python abort使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了abort函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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


注:本文中的webapp2.abort函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。