def post(self): template = dao.get_template_by_id(self.request.get(u'template_id')) if not dao.test_template_permissions( template, [dao.TEMPLATE_OWN, dao.TEMPLATE_EDIT]): webapp2.abort(401) document_entity = dao.get_document_by_id( template, self.request.get(u'document_id')) error_msg = None if document_entity else u'Unable to access specified document' # Handle delete request if document_entity and self.request.get(u'delete'): try: document_entity.key.delete() self.redirect("/template/document?template_id={}".format( template.key.id())) return except Exception as e: error_msg = u'Deleting document from template failed: {}'.format( e) # Handle update request if document_entity and self.request.get(u'update'): try: document_entity.description = self.request.get(u'description') document_entity.style_name = self.request.get(u'doc_style') document_entity.put() self.redirect("/template/document?template_id={}".format( template.key.id())) return except Exception as e: error_msg = u'Updating document failed: {}'.format(e) # Display the webpage self.render(template, document_entity, error_msg)
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)
def _get_user(): user = users.get_current_user() if not user: webapp2.abort(400, "User needs to be logged in") user.jerry_profile = _get_jerry_provider().signin(user.user_id()) return user
def get(self): template = dao.get_template_by_id(self.request.get(u'template_id')) if not dao.test_template_permissions( template, [dao.TEMPLATE_OWN, dao.TEMPLATE_EDIT]): webapp2.abort(401) variable_list = list() for variable_entity in dao.get_variables(template): variable = dict() variable[u'id'] = variable_entity.key.id() variable[u'name'] = variable_entity.name variable[u'description'] = variable_entity.description variable[u'is_repeating'] = variable_entity.is_repeating variable[u'input_field'] = variable_entity.input_field variable[u'assignments'] = self.get_assignments(template, variable) variable[u'documents'] = self.get_documents(template, variable) variable_list.append(variable) # Create template and template values, render the page jinja_template = ui.get_template(self, u'template/variable/index.html') jinja_template_values = dao.get_standard_template_values(template) jinja_template_values[u'variables'] = variable_list self.response.out.write(jinja_template.render(jinja_template_values))
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 ] }
def get(self): project = dao.get_project_by_id(self.request.get(u'_project_id')) if not dao.test_project_permissions(project, []): webapp2.abort(401) interview_service = InterviewService(project) interview_name = self.request.get(u'_interview_name') interview = interview_service.get_interview_by_name(interview_name) variable = dao.get_variable_by_internal_name(project, self.request.get(u'_variable_name')) index = self.request.get(u'_index') # Deliver HTTP response jinja_template = ui.get_template(self, u'project/upload_file.html') jinja_template_values = dao.get_standard_project_values(project) jinja_template_values[u'interview'] = interview jinja_template_values[u'variable'] = variable if index: jinja_template_values[u'show_index'] = True jinja_template_values[u'index'] = index jinja_template_values[u'upload_file_post_url'] = blobstore.create_upload_url('/project/upload_file_post') self.response.out.write(jinja_template.render(jinja_template_values))
def post(self): project = dao.get_project_by_id(self.request.get(u'project_id')) if not dao.test_project_permissions(project, [dao.PROJECT_OWN, dao.PROJECT_MANAGE]): webapp2.abort(401) name = self.request.get(u'name') description = self.request.get(u'description') css = self.request.get(u'css') if not name: error_msg = u'You must specify a name for your style definition' else: style_entity = dao.get_style_by_name(project, name) if style_entity: error_msg = u'Adding style failed: Duplicate style name in project' else: try: dao.Style(name=name, description=description, css=css, parent=project.key).put() dao.touch_project_documents(project) self.redirect("/project/style?project_id={}".format(project.key.id())) return except Exception as e: error_msg = u'Adding style failed: {}'.format(e) # Display the webpage self.render(project, error_msg)
def post(self): template = dao.get_template_by_id(self.request.get(u'template_id')) if not dao.test_template_permissions(template, [dao.TEMPLATE_OWN, dao.TEMPLATE_EDIT]): webapp2.abort(401) name = self.request.get(u'name') description = self.request.get(u'description') doc_style = self.request.get(u'doc_style') if not name: error_msg = u'You must specify a name for your document definition' else: document_entity = dao.get_document_by_name(template, name) if document_entity: error_msg = u'Adding document failed: Duplicate document name in template' else: try: document_entity = dao.Document(name=name, internal_name=dao.convert_name_to_internal_name(name), description=description, style_name=doc_style, parent=template.key) document_entity.put() self.redirect("/template/document?template_id={}".format(template.key.id())) return except Exception as e: error_msg = u'Adding document failed: {}'.format(e) # Display the webpage self.render(template, error_msg)
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)
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))
def post(self): id = long(self.request.get("id")) artwork_json = json.loads(self.request.get("json")) crop_tuple = tuple(float(x) for x in json.loads(self.request.get("crop"))) target_artwork = FeaturedArtwork.get_by_id(id) if not target_artwork: webapp2.abort(404) target_artwork.title = artwork_json["title"] target_artwork.byline = artwork_json["byline"] target_artwork.attribution = artwork_json["attribution"] if "attribution" in artwork_json else None new_image_url, new_thumb_url = backroomarthelper.maybe_process_image( artwork_json["imageUri"], crop_tuple, target_artwork.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"] target_artwork.image_url = new_image_url target_artwork.thumb_url = new_thumb_url target_artwork.details_url = artwork_json["detailsUri"] target_artwork.save() self.response.set_status(200) self.response.out.write(json.dumps(artwork_dict(target_artwork)))
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'
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))
def post(self): if not dao.test_site_permission(dao.SITE_ADMIN_USERS): webapp2.abort(401) # Get specified Project entity name = self.request.get(u'name') project_or_template_type = self.request.get( u'project_or_template_type') email = self.request.get(u'email') selected_project = None error_msg = None for project in dao.get_projects_or_templates_by_name(name): if project.project_type == project_or_template_type: if dao.get_project_user_by_email(project, email): if not selected_project: selected_project = project else: error_msg = u'Multiple {} with specified name/email/type; don\'t know which one to delete'.format( u'projects' if project_or_template_type == dao.PROJECT else u'templates') if not selected_project: error_msg = u'Name/email/type combination not found' if not error_msg and self.request.get(u'delete'): # Handle delete request try: dao.delete_project(selected_project) self.redirect("/") return except Exception as e: error_msg = u'Deleting project or template failed: {}'.format( e) # Display the webpage self.render(error_msg)
def get(self): project = dao.get_project_by_id(self.request.get(u'project_id')) if not dao.test_project_permissions(project, [dao.PROJECT_OWN, dao.PROJECT_MANAGE]): webapp2.abort(401) # Display the webpage self.render(project)
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)
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)
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)
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)
def post(self): if not dao.test_site_permission(dao.SITE_ADMIN_USERS): webapp2.abort(401) # Get specified Template entity template_id = self.request.get(u'template_id') template = dao.get_template_by_id(template_id) error_msg = None if template else u'Unable to access specified template' # Handle delete request if template and self.request.get(u'delete'): try: dao.delete_project(template) self.redirect("/site_admin/template_admin") return except Exception as e: error_msg = u'Deleting template failed: {}'.format(e) # Handle update request if template and self.request.get(u'update'): try: template.description = self.request.get(u'description') if not template.description: raise Exception( u'You must provide a description for the template') template.status = self.request.get(u'status') template.put() self.redirect("/site_admin/template_admin") return except Exception as e: error_msg = u'Updating template failed: {}'.format(e) # Display the webpage self.render(template_id, template, error_msg)
def get(self, report_id): try: report = ndb.Key(urlsafe=report_id).get() except: webapp2.abort(404) self.response.write(report.to_html())
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))
def build_manifest(appname, set_icons=True): """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['description'] = app_data.DEFAULT_DESCRIPTION manifest['short_name'] = app_data.DEFAULT_SHORT_NAME if set_icons: manifest['icons'] = app_data.DEFAULT_ICONS manifest['display'] = app_data.DEFAULT_DISPLAY manifest['start_url'] = app_data.DEFAULT_START_URL manifest['file_handler'] = app_data.DEFAULT_FILE_HANDLER FIELDS = ('icons', 'display', 'related_applications', 'prefer_related_applications', 'file_handler') 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'
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)
def post(self): project = dao.get_project_by_id(self.request.get(u'project_id')) if not dao.test_project_permissions(project, [dao.PROJECT_OWN, dao.PROJECT_MANAGE]): webapp2.abort(401) style_entity = dao.get_style_by_id(project, self.request.get(u'style_id')) error_msg = None if style_entity else u'Unable to access specified style' # Handle delete request if style_entity and self.request.get(u'delete'): try: style_entity.key.delete() dao.touch_project_documents(project) self.redirect("/project/style?project_id={}".format(project.key.id())) return except Exception as e: error_msg = u'Deleting style from project failed: {}'.format(e) # Handle update request if style_entity and self.request.get(u'update'): try: style_entity.description = self.request.get(u'description') style_entity.css = self.request.get(u'css') style_entity.put() dao.touch_project_documents(project) self.redirect("/project/style?project_id={}".format(project.key.id())) return except Exception as e: error_msg = u'Updating style failed: {}'.format(e) # Display the webpage self.render(project, style_entity, error_msg)
def post(self, id=None): if id: depart_date = json.loads(self.request.body) #get departure date from json body for departing boat b = ndb.Key(urlsafe=id).get() #get the boat object from the database if b.at_sea == True: webapp2.abort(400,"Boat is not in a slip.") for slip in Slip.query().fetch(): #fetch all slips from the database if slip.current_boat == str(id): s = slip #check data is correct type if isinstance(depart_date['depart'], basestring) == False: webapp2.abort(400,"Bad user input. Give json string with 'depart' and 'date' where date is a string") #add departure history to slip departure = "departed boat: " + str(s.current_boat) + ", departure date: " + str(depart_date["depart"]) s.departure_history.append(departure) #update data s.current_boat = None s.arrival_date = None b.at_sea = True #update server s.put() b.put()
def default_get(_, uid): item = Model.get_by_id(uid) if item is None: abort(400, 'No Resource for that id') visible_fields = getattr(Model, 'VISIBLE_FIELDS', None) return item.to_dict(include=visible_fields)
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)
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))
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))
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))
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)
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?"}))
def patch(self, id=None): if id: w = ndb.Key( urlsafe=id).get() #get the object instance from the database if self.request.body: #check if user sent data. If not, abort error 404 new_data = json.loads(self.request.body) else: webapp2.abort(400, "Bad user input") #replace data if it is there. if isinstance(new_data.get('name', None), basestring): w.name = new_data['name'] if isinstance(new_data.get('date', None), basestring): w.date = new_data['date'] if isinstance(new_data.get('type', None), basestring): w.type = new_data['type'] if isinstance(new_data.get('notes', None), basestring): w.notes = new_data['notes'] w.put() #put new info on database w_d = w.to_dict() ###debugging self.response.write(json.dumps(w_d)) ###debugging else: self.response.write("patch to WorkoutHandler") #debugging
def post(self): project = dao.get_project_by_id(self.request.get(u'project_id')) if not dao.test_project_permissions( project, [dao.PROJECT_OWN, dao.PROJECT_MANAGE]): webapp2.abort(401) name = self.request.get(u'name') description = self.request.get(u'description') doc_style = self.request.get(u'doc_style') if not name: error_msg = u'You must specify a name for your document definition' else: document_entity = dao.get_document_by_name(project, name) if document_entity: error_msg = u'Adding document failed: Duplicate document name in project' else: try: document_entity = dao.Document( name=name, internal_name=dao.convert_name_to_internal_name(name), description=description, style_name=doc_style, parent=project.key) document_entity.put() dao.touch_project_documents(project) self.redirect("/project/document?project_id={}".format( project.key.id())) return except Exception as e: error_msg = u'Adding document failed: {}'.format(e) # Display the webpage self.render(project, error_msg)
def get(self, path='', status_code=None): path = path.lstrip('/') path = os.path.join(pod_root_path, 'build', path) if os.path.isdir(path): path = path.rstrip('/') + '/index.html' logging.info('Serving -> {}'.format(path)) if not os.path.isfile(path): if custom_404_page: return self.get(custom_404_page, status_code=404) else: webapp2.abort(404) if status_code is not None: self.response.set_status(status_code) with open(path, 'rb') as fp: etag = StaticHandler.get_etag(path) weak_etag = 'W/{}'.format(etag) request_etag = self.request.headers.get('If-None-Match') if request_etag in [etag, weak_etag]: self.response.status = 304 del self.response.headers['Content-Type'] return content_type = mimetypes.guess_type(path)[0] or 'text/plain' self.response.headers['ETag'] = str(etag) self.response.headers['Content-Type'] = content_type if supplemental_headers: self.response.headers.update(supplemental_headers) # Bypass the subclass's `write` method due to Python 3 incompatibility. # https://github.com/GoogleCloudPlatform/webapp2/issues/146 super(webapp2.Response, self.response).write(fp.read())
def post(self): project = dao.get_project_by_id(self.request.get(u'project_id')) if not dao.test_project_permissions( project, [dao.PROJECT_OWN, dao.PROJECT_MANAGE]): webapp2.abort(401) name = self.request.get(u'name') description = self.request.get(u'description') variable_type = self.request.get(u'type') if not name: error_msg = u'You must specify a name for your assignment definition' elif not variable_type: error_msg = u'You must specify whether this is a single or repeating assignment' else: assignment_entity = dao.get_assignment_by_name(project, name) if assignment_entity: error_msg = u'Adding assignment failed: Duplicate assignment name in project' else: try: assignment_entity = dao.Assignment( name=name, description=description, is_repeating=(variable_type == u'repeating'), parent=project.key) assignment_entity.put() dao.touch_project_assignments(project) self.redirect("/project/assignment?project_id={}".format( project.key.id())) return except Exception as e: error_msg = u'Adding assignment failed: {}'.format(e) # Display the webpage self.render(project, error_msg)
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))
def post(self): template = dao.get_template_by_id(self.request.get(u'template_id')) if not dao.test_template_permissions( template, [dao.TEMPLATE_OWN, dao.TEMPLATE_EDIT]): webapp2.abort(401) name = self.request.get(u'name') description = self.request.get(u'description') variable_type = self.request.get(u'type') if not name: error_msg = u'You must specify a name for your assignment definition' elif not variable_type: error_msg = u'You must specify whether this is a single or repeating assignment' else: assignment_entity = dao.get_assignment_by_name(template, name) if assignment_entity: error_msg = u'Adding assignment failed: Duplicate assignment name in template' else: try: assignment_entity = dao.Assignment( name=name, description=description, is_repeating=(variable_type == u'repeating'), parent=template.key) assignment_entity.put() self.redirect("/template/assignment?template_id={}".format( template.key.id())) return except Exception as e: error_msg = u'Adding assignment failed: {}'.format(e) # Display the webpage self.render(template, error_msg)
def get(self): if (users.is_current_user_admin() or self.request.headers.get('X-Appengine-Cron') == 'true'): models.delete_all_comments() self.response.set_status(204) else: webapp2.abort(403)
def post(self): if not dao.test_current_user_registered(): webapp2.abort(401) current_user = users.get_current_user() current_email = current_user.email().lower() # Attempt to create a new template try: name = self.request.get(u'name').strip() if not name: raise Exception(u'You must provide a name for your template') for template in dao.get_private_template_by_name(name): if dao.test_email_is_template_owner(template, current_email): raise Exception(u'Sorry, you already own a template by that name') # Create the new Project entity template = dao.Project(name=name, project_type=dao.PRIVATE_TEMPLATE, description=self.request.get(u'description')) template_key = template.put() # Create a ProjectUser entity, making the current user owner of the new template dao.ProjectUser(email=dao.get_current_site_user().email, permissions=[dao.TEMPLATE_OWN], parent=template_key).put() self.redirect("/template?template_id={}".format(template_key.id())) return except Exception as e: error_msg = u'Creating template failed: {}'.format(e) # Display the webpage self.render(error_msg)
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))
def checkPerm(self): user = models.Author.getUser() if user is None or not user.isAdmin(): webapp2.abort(403) return user
def post(self, token): self.response.headers["Content-Type"] = "text/html" logging.info("Got token " + token) messager = db.GqlQuery( "SELECT * " "FROM Messager " "WHERE token = :1 " "ORDER BY date DESC LIMIT 1", token ).get() if messager == None: webapp2.abort(404) post_message = self.request.get("messager[message]") post_enabled = self.request.get("messager[enabled]") messager.message = post_message logging.info("Got enabled " + post_enabled) if post_enabled == "1": messager.enabled = True else: messager.enabled = False messager.put() template_values = {"messager": messager, "updated": True} template = jinja_environment.get_template("templates/messges_edit.html") self.response.out.write(template.render(template_values))
def checkPerm(self): user = models.Author.getUser() if user is None or not user.canCreate: webapp2.abort(403) return user
def decodeJWTView(request): """Processes POST request and sends decoded JWT as pretty printed JSON object. Args: request: A HTTP request object. Returns: A pretty printed JSON object if valid jwt is present, returns a HTTP 404 otherwise. """ input_jwt = request.POST.get('jwt', None) if not input_jwt: webapp2.abort(404) try: input_jwt = unicodedata.normalize(NORMAL_FORM, input_jwt).encode('ascii', 'ignore') # Append extra characters to make original string base 64 decodable. input_jwt += '=' * (4 - (len(input_jwt) % 4)) decoded_jwt = base64.urlsafe_b64decode(input_jwt) except JSONDecodeError as e: result = {'error': True} webapp2.abort(404) else: decoded_jwt = json.loads(decoded_jwt) return webapp2.Response(json.dumps(decoded_jwt, indent=8))
def validate(self): request = webapp2.get_request() data = json.decode(request.body) if not isinstance(data, dict): webapp2.abort(403, detail='not a dict') for f in self.fields: if not f.id in self.validations: continue try: value = data[f.id].strip() except KeyError: value = '' self.field_values[f.id] = value for val in self.validations[f.id]: val.input = f.id if not val.validate(self): webapp2.abort(403, detail='validation error, id: %s name: %s value: %s' % (f.id, f.name, value)) return self.field_values
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 = 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)
def _get_grapl_params(self): try: request_data = self.request.json_body if isinstance(request_data, six.string_types): request_data = dict(query=request_data) except: request_data = {} request_data.update(dict(self.request.GET)) query = request_data.get('query', self.request.body) if not query: webapp2.abort(400, "Query is empty.") operation_name = request_data.get('operation_name') variables = request_data.get('variables') if variables and isinstance(variables, six.text_type): try: variables = json.loads(variables) except: raise webapp2.abort(400, 'Variables are invalid JSON.') pretty = request_data.get('pretty') return query, operation_name, variables, pretty
def post(self): id = long(self.request.get('id')) artwork_json = json.loads(self.request.get('json')) crop_tuple = tuple(float(x) for x in json.loads(self.request.get('crop'))) target_artwork = FeaturedArtwork.get_by_id(id) if not target_artwork: webapp2.abort(404) target_artwork.title = artwork_json['title'] target_artwork.byline = artwork_json['byline'] target_artwork.attribution = artwork_json['attribution'] if 'attribution' in artwork_json else None new_image_url, new_thumb_url = maybe_process_image( artwork_json['imageUri'], crop_tuple, target_artwork.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'] target_artwork.image_url = new_image_url target_artwork.thumb_url = new_thumb_url target_artwork.details_url = artwork_json['detailsUri'] target_artwork.save() self.response.set_status(200) self.response.out.write(json.dumps(artwork_dict(target_artwork)))
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))
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)
def post(self): if not dao.test_site_permission(dao.SITE_ADMIN_USERS): webapp2.abort(401) # Get specified SiteUser entity site_user_id = self.request.get(u'site_user_id') site_user = dao.get_site_user_by_id(site_user_id) error_msg = None if site_user else u'Unable to access specified site user' # Handle delete request if site_user and self.request.get(u'delete'): try: site_user.key.delete() self.redirect("/site_admin/site_user_admin") return except Exception as e: error_msg = u'Deleting site user failed: {}'.format(e) # Handle update request if site_user and self.request.get(u'update'): # Attempt to update the SiteUser entity's permissions permissions = list() for permission in dao.get_all_site_permissions(): if self.request.get(permission): permissions.append(permission) site_user.site_permissions = permissions try: site_user.put() self.redirect("/site_admin/site_user_admin") return except Exception as e: error_msg = u'Updating site user failed: {}'.format(e) # Display the webpage self.render(site_user_id, site_user, error_msg)
def post(self): id = long(self.request.get('id')) artwork_json = json.loads(self.request.get('json')) crop_tuple = tuple( float(x) for x in json.loads(self.request.get('crop'))) target_artwork = FeaturedArtwork.get_by_id(id) if not target_artwork: webapp2.abort(404) target_artwork.title = artwork_json['title'] target_artwork.byline = artwork_json['byline'] target_artwork.attribution = artwork_json[ 'attribution'] if 'attribution' in artwork_json else None new_image_url, new_thumb_url = backroomarthelper.maybe_process_image( artwork_json['imageUri'], crop_tuple, target_artwork.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'] target_artwork.image_url = new_image_url target_artwork.thumb_url = new_thumb_url target_artwork.details_url = artwork_json['detailsUri'] target_artwork.save() self.response.set_status(200) self.response.out.write(json.dumps(artwork_dict(target_artwork)))
def delete(self, note_id): if not users.get_current_user(): webapp2.abort(401) iden = int(note_id) note = db.get(db.Key.from_path('Note', iden)) db.delete(note) return self.redirect('/note/list')
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)
def _get_grapl_params(self): try: request_data = self.request.json_body if isinstance(request_data, six.string_types): request_data = dict(query=request_data) except: try: request_data = json.loads(self.request.body) except ValueError: request_data = {} request_data.update(dict(self.request.GET)) query = request_data.get('query', self.request.body) if not query: webapp2.abort(400, "Query is empty.") operation_name = request_data.get('operation_name') variables = request_data.get('variables') if variables and isinstance(variables, six.text_type): try: variables = json.loads(variables) except: raise webapp2.abort(400, 'Variables are invalid JSON.') pretty = request_data.get('pretty') return query, operation_name, variables, pretty
def check_login_before(request, *args, **kwargs): if not users.get_current_user(): # If handler has no login_url specified invoke a 403 error try: webapp2.redirect(users.create_login_url(request.uri).replace("use_json","x"), abort=True) except (AttributeError, KeyError), e: webapp2.abort(403)