def main(): application = WSGIApplication([('/oauth/(.*)/(.*)', OAuthHandler), ('/', MainHandler)], debug=True) CGIHandler().run(application)
def main(): urlconf = [ (r'/(\d+)/', ProjectHandler), (r'/', DashboardHandler), ] debug = os.environ['SERVER_SOFTWARE'].startswith('Development') application = WSGIApplication(urlconf, debug=debug) run_wsgi_app(application)
def main(): application = WSGIApplication([ ('/', IndexHandler), ('/login', LoginHandler), ('/list', ListHandler), ('/_ah/xmpp/message/chat/', XMPPHandler), ('.*', NotFoundHandler), ], debug=True) run_wsgi_app(application)
def main(): application = WSGIApplication([ ('/oauth/weibo/login', SinaLogin), ('/oauth/weibo/logout', SinaLogout), ('/oauth/weibo/callback', SinaCallback), ('/oauth/weibo/newuser', NewSinaUser), ('/weibo/greader.settings', Weibo), ('/weibo/greader', WeiboIndex), ('/oauth/weibo/test', SinaTest) ], debug=True) CGIHandler().run(application)
if url: logger.debug('redirector memcache_hit link:%s target_url:%s', link, url) memcache_hit = True else: logger.debug('redirector memcache_miss link:%s target_url:%s', link, url) url = str(Link.get_by_id(link).target_url) memcache_hit = False deferred.defer(log, os.environ['REQUEST_LOG_ID'], memcache_hit, link, url, handler.request.cookies) return url app = WSGIApplication([ Route('/images/cleardot.gif', Cookie, methods=['GET']), Route('/', Create, methods=['POST']), Route('/<path>', RedirectHandler, methods=['GET'], defaults={'_uri': redirector}), Route('/', RedirectHandler, methods=['GET'], defaults={'_uri': 'http://detroitartmap.com'}), ], debug=True) if __name__ == "__main__": run_wsgi_app(app)
if self.request.accept.accept_html(): self.resource["commands"] = self.resource["commands"][:10] self.writeWithTemplate(self.resource, "Command") else: self.writeJson(self.resource) def post(self): try: odenki_user = getCurrentUser() except OdenkiUserNotFound: self.response.set_status(401) return #assert isinstance(odenki_user, OdenkiUser) parsed_json = loads(self.request.body) parsed_json["userId"] = odenki_user.odenkiId try: renewCommand(parsed_json) except (CommandNotFound, KeyError): registerCommand(parsed_json) self.get() def delete(self): pass if __name__ == "__main__": getLogger().setLevel(DEBUG) application = WSGIApplication([('/Command', _RequestHandler)], debug=True) run_wsgi_app(application)
output=output, exception=ex, start_at=start_at, stop_at=stop_at) model.put() def _report_by_mail(self, version): from google.appengine.api import mail email = mail.EmailMessage() email.sender = "*****@*****.**" email.subject = "Node.js new version released: %s" % (version, ) email.to = "Makoto Kuwata <*****@*****.**>" email.body = ("Node.js new version released: %s\n") % (version, ) email.send() ## main application routing = [ ('/.*', VersionWatcherHandler), ] application = WSGIApplication(routing, debug=True) ## main routine def main(): run_wsgi_app(application) if __name__ == "__main__": main()
def get(self): query = Post.query(Post.media_key == None) for post_key in query.iter(keys_only=True): taskqueue.add(url='/backburner/download_post_media', params={'post': post_key.urlsafe()}) def store_picture_from_content(content, mime_type='application/octet-stream'): img = Image(content) img.resize(width=800, height=800) img.im_feeling_lucky() img_type = PNG if 'png' in mime_type else JPEG img = img.execute_transforms(output_encoding=img_type) # create file file_name = files.blobstore.create(mime_type=mime_type) with files.open(file_name, 'a') as f: f.write(img) # Finalize the file files.finalize(file_name) # Get the file's blob key blob_key = files.blobstore.get_blob_key(file_name) return get_serving_url(blob_key), blob_key app = WSGIApplication([ ('/backburner/download_post_media', MediaDownloader), ('/backburner/download_missing', DownloadMissingMediaJob), ], debug=True)
def main(): application = WSGIApplication([ ('/cron/feeding', FeedingHandler), ], debug=True) run_wsgi_app(application)
from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext.webapp import WSGIApplication import request_handler import user_util class RedirectGTV(request_handler.RequestHandler): @user_util.open_access def get(self): self.redirect("/gtv/") application = WSGIApplication([ ('/gtv', RedirectGTV), ]) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
upload = self.get_uploads()[0] SpaceShip.save_from_request(self.request, upload) except Exception as e: self.error(403) logging.exception(e) self.response.out.write(e) return self.redirect('/spaceships') class SpaceShipsHandler(blobstore_handlers.BlobstoreUploadHandler): def get(self): """ Display a SpaceShip creation form """ ships = SpaceShip.query().fetch() html = render('spaceships.html', {'ships': ships}) self.response.write(html) app = WSGIApplication([ ('/spaceships', SpaceShipsHandler), ('/create_spaceship', SpaceShipHandler), ('/create_location', LocationHandler), (r'/star_trip/?(?P<trip_id>[\w-]*)', StarTripHandler), ('/.*', HomeHandler), ], debug=True) def render(tmpl_file, values={}): path = join(dirname(__file__), 'templates', tmpl_file) return template.render(path, values)
from google.appengine.ext.webapp import WSGIApplication from google.appengine.ext.webapp.util import run_wsgi_app from handlers import AccountHandler, AdminHandler, BadgeHandler, \ BadgesHandler, BadgeApplicationHandler, CalendarHandler, ContactHandler, \ FAQHandler, FileNotFoundHandler, HackathonHandler, LoginHandler, \ ManualHandler, MasterclassHandler, MemberHandler, MembersHandler, \ MessagesHandler, NewsHandler, TalksHandler application = WSGIApplication( (('/', NewsHandler), ('/account', AccountHandler), ('/admin', AdminHandler), ('/badges', BadgesHandler), ('/badges/([^/]+)', BadgeHandler), ('/badge_application', BadgeApplicationHandler), ('/calendar', CalendarHandler), ('/contact', ContactHandler), ('/faq', FAQHandler), ('/hack-a-thon', HackathonHandler), ('/login', LoginHandler), ('/manual', ManualHandler), ('/masterclass', MasterclassHandler), ('/members', MembersHandler), ('/members/([^/]+)', MemberHandler), ('/messages/([^/]+)', MessagesHandler), ('/talks', TalksHandler), ('/(.+)', FileNotFoundHandler)), debug=True) def main(argv=None): if argv is None: argv = sys.argv run_wsgi_app(application) return 0
# WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANDABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #------------------------------------------------------------------------------ import logging from google.appengine.ext.webapp import WSGIApplication from google.appengine.ext.webapp.util import run_wsgi_app from openpowersystem.handlers import MainPage, UploadPage, JSONHandler logging.getLogger().setLevel(logging.DEBUG) application = WSGIApplication([('/', MainPage), ('/upload', UploadPage), ('/json', JSONHandler)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main() # EOF -------------------------------------------------------------------------
from google.appengine.ext.webapp import WSGIApplication from google.appengine.ext.webapp.util import run_wsgi_app from mail import SendMail application = WSGIApplication([ ('/', SendMail), ], debug=True) def main(): run_wsgi_app(application) if __name__ == '__main__': main()
post_id = comment.post.id() comment.key.delete() logging.info("Comment {} deleted".format(comment_id)) self.redirect('/post/' + str(post_id)) else: self.redirect('/') class RunTestHandler(RequestHandler): def get(self): result = run_from_gae() self.response.out.write(result.replace('\n', '<br/>')) app = WSGIApplication([ ('/hello', MainHandler), ('/', HomeHandler), ('/post/create', PostCreateHandler), ('/post/(?P<post_id>\d+)/delete', PostDeleteHandler), (r'/post/(?P<post_id>\d+)', PostHandler), (r'/post/(?P<post_id>\d+)/like', LikePostHandler), (r'/comment/(?P<comment_id>\d+)/delete', CommentDeleteHandler), (r'/test', RunTestHandler), ], debug=True) def render(tmpl_file, values={}): path = join(dirname(__file__), 'templates', tmpl_file) return template.render(path, values)
import os from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext.webapp import WSGIApplication, template, RequestHandler class RedirectGTV(RequestHandler): def get(self): self.redirect("/gtv/") class ViewGTV(RequestHandler): def get(self): path = os.path.join(os.path.dirname(__file__), "index.html") self.response.out.write(template.render(path, {})) application = WSGIApplication([ ('/gtv/', ViewGTV), ('/gtv', RedirectGTV), ]) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
def main(): application = WSGIApplication(handlers, debug=True) CGIHandler().run(application)
def main(): """ Web application main controller """ application = WSGIApplication(ROUTES, debug=True) run_wsgi_app(application)
except Exception, exception: logging.exception(exception) retries = int( self.request.headers['X-AppEngine-TaskExecutioncount']) already_broken = self.request.headers[ 'X-AppEngine-Queuename'] == BROKEN_TASK_QUEUE if already_broken or MAX_RETRY_COUNT is None or retries < MAX_RETRY_COUNT: # Failing normally self.error(500) else: logging.info( "Retrying this task on the broken-tasks queue from now on") # Reinserting task onto the brokentask queue task = taskqueue.Task(payload=self.request.body, countdown=2.0, url=deferred._DEFAULT_URL, headers=deferred._TASKQUEUE_HEADERS) task.add(BROKEN_TASK_QUEUE) application = WSGIApplication([(".*", LimitedTaskHandler)]) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
class _RequestHandler(MyRequestHandler): def get(self): try: getCurrentUser() except: self.response.set_status(401) self.redirect("/OdenkiUser") return folder = getOdenkiFolder() assert isinstance(folder, Resource) spreadsheet = getOdenkiSpreadsheet() assert isinstance(spreadsheet, Resource) command_worksheet = getCommandWorksheet() assert isinstance(command_worksheet, WorksheetEntry) v = {} v["folder_title"] = folder.title v["folder_id"] = folder.resource_id v["folder_link"] = folder.find_html_link() v["spreadsheet_title"] = spreadsheet.title v["spreadsheet_id"] = spreadsheet.resource_id v["spreadsheet_link"] = spreadsheet.find_html_link() v["command_worksheet_link"] = spreadsheet.find_html_link( ) + "#gid=" + str(getWorksheetGid(command_worksheet.GetWorksheetId())) self.writeWithTemplate(v, "Spreadsheet") if __name__ == "__main__": application = WSGIApplication([('/Spreadsheet', _RequestHandler)], debug=True) run_wsgi_app(application)
assert isinstance(access_token, OAuthHmacToken) saveAccessToken(access_token) except Exception, e: logging.debug("Can't get access token. " + e.message) deleteAccessToken() deleteRequestToken() self.redirect("/OdenkiUser") return assert loadAccessToken() is not None try: resource_feed = getResources() assert isinstance(resource_feed, ResourceFeed) except Unauthorized, e: deleteRequestToken() deleteAccessToken() self.redirect("/GoogleDocs") return self.redirect("/OdenkiUser") return if __name__ == "__main__": logging.getLogger().setLevel(logging.DEBUG) application = WSGIApplication([('/GoogleDocs', _RequestHandler), ('/GoogleDocs', _RequestHandler), ('/GoogleDocs', _RequestHandler)], debug=True) run_wsgi_app(application)
MasterclassHandler, MemberHandler, MembersHandler, \ MessagesHandler, MeetingHandler, NewsHandler, NewsLetterHandler, NewsLetterTaskHandler, \ TalksHandler, TeamsHandler, TeamSubmissionHandler application = WSGIApplication( (('/' , NewsHandler), ('/account' , AccountHandler), ('/admin' , AdminHandler), ('/badges' , BadgesHandler), ('/badges/([^/]+)' , BadgeHandler), ('/badge_application' , BadgeApplicationHandler), ('/calendar' , CalendarHandler), ('/contact' , ContactHandler), ('/faq' , FAQHandler), ('/hack-a-thon' , HackathonHandler), ('/login' , LoginHandler), ('/manual' , ManualHandler), ('/masterclass' , MasterclassHandler), ('/members' , MembersHandler), ('/members/([^/]+)' , MemberHandler), ('/messages/(\d+)' , MessagesHandler), ('/newsletter' , NewsLetterHandler), ('/task/newsletter' , NewsLetterTaskHandler), ('/task/meeting' , MeetingHandler), ('/talk' , TalksHandler), ('/teams' , TeamsHandler), ('/team_submission' , TeamSubmissionHandler)), debug=True) def main(argv=None): if argv is None: argv = sys.argv
from handlers import AccountHandler, AdminNewsHandler, AdminHandler, \ BadgeHandler, BadgesHandler, BadgeApplicationHandler, CalendarHandler, \ ContactHandler, EditHandler, FAQHandler, FileNotFoundHandler, \ HackathonHandler, LoginHandler, ManualHandler, MemberHandler, \ MembersHandler, MessagesHandler, NewsHandler, TalksHandler register_template_library('templatetags.customtags') application = WSGIApplication( ((r'^/$', NewsHandler), (r'^/news$', NewsHandler), (r'^/account$', AccountHandler), (r'^/admin$', AdminHandler), (r'^/admin/news$', AdminNewsHandler), (r'^/admin/news/([^/]+)$', EditHandler), (r'^/badges/$', BadgesHandler), (r'^/badges/([^/]+)$', BadgeHandler), (r'^/badge_application$', BadgeApplicationHandler), (r'^/calendar$', CalendarHandler), (r'^/contact$', ContactHandler), (r'^/faq$', FAQHandler), (r'^/hack-a-thon$', HackathonHandler), (r'^/login$', LoginHandler), (r'^/manual$', ManualHandler), (r'^/members/$', MembersHandler), (r'^/members/([^/]+)$', MemberHandler), (r'^/messages/(\d+)$', MessagesHandler), (r'^/talks$', TalksHandler), (r'(.*)', FileNotFoundHandler)), debug=True) def main(argv=None): if argv is None: argv = sys.argv run_wsgi_app(application) return 0
self.assertEqual(_Hello.body, '{"c": "d", "s": false}') self.assertEqual(_Hello.arguments, ["a", "v"]) self.assertEqual(_Hello.headers["Content-Type"], 'application/json; charset="utf-8"') # def testPost(self): # response = self.testapp.post_json(b"/api/Relays/product1/serial1/module1", {"a": "b"}) def testDict(self): xx = {"1": "2", "3": "4"} for x, y in xx.iteritems(): print(x, y) def tearDown(self): self.testbed.deactivate() if __name__ == "__main__": import os if os.environ.get("APPENGINE_RUNTIME"): from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext.webapp import WSGIApplication wsgi_application = WSGIApplication(maps, debug=True) run_wsgi_app(wsgi_application) else: import unittest unittest.main()
at_least_one = False for k, v in self.request.params.iteritems(): try: v = int(v) except: if v.startswith('dt:'): v = parse_datetime(v[3:]) setattr(instance, k, v) at_least_one = True if not at_least_one: self.response.out.write("Expected: at least one query param") return instance.put() self.response.out.write(simplejson.dumps(expando_to_properties(instance))) app = WSGIApplication([ ('/rest/([\w\d-]+)/([\w\d_]+)/', QueryHandler), ('/rest/([\w\d-]+)/([\w\d_]+)/count', CountHandler), ('/rest/([\w\d-]+)/([\w\d_]+)/put', SaveHandler), ('/rest/([\w\d-]+)/([\w\d_]+)/([\w\d_]+)', GetHandler), ]) def main(): run_wsgi_app(app) if __name__ == '__main__': main()
import logging from google.appengine.ext.webapp import RequestHandler, WSGIApplication from google.appengine.api.taskqueue import Task from models import TopLocations class RunRollupHandler(RequestHandler): def get(self): msg = "Starting Rollup of Top Locations" logging.info(msg) Task(url='/rollup/top_locations', target='rollup').add(queue_name='default') self.response.out.write(msg) def post(self): TopLocations.run() app = WSGIApplication([ ('/rollup/top_locations', RunRollupHandler), ], debug=True)
titulo_pagina = 'Aprenda a programar' miolo = '<a href="/req">A requisição</a>' self.response.out.write(ENVELOPE % locals()) def prep(o): ''' prepara objeto para saída html ''' return escape(pformat(o)) class Requisicao(RequestHandler): def get(self): titulo_pagina = 'A requisição' req = self.request miolo = [] miolo.append('<pre>%s</pre>' % prep(req)) miolo.append('<pre>%s</pre>' % prep(dir(req))) miolo.append('<pre>') for atrib in (a for a in dir(req) if not any((a.startswith('_'), a.endswith('environ')))): miolo.append('%28s = %s' % (atrib, prep(getattr(req, atrib)))) miolo.append('</pre>') miolo.append('<pre>%s</pre>' % prep(req.environ)) miolo = '\n'.join(miolo) self.response.out.write(ENVELOPE % locals()) if __name__ == '__main__': aplicacao = WSGIApplication([ ('/', Principal), ('/req', Requisicao), ], debug=True) run_wsgi_app(aplicacao)