• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python webapp2.get_app函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



在下文中一共展示了get_app函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: post

    def post(self, modelName):
        """
        Create new instance of model.
        Usage: HTTP POST to /rest/ModelName with ContentType=application/json
        Input:
        {
            "property_name": property_value,
            ...
        }
        Returns:
        {
            "status": "success",
            "data": id
        }

        Where id is the numeric integer ID of the newly-created model.
        See the description if id() for details:
        https://developers.google.com/appengine/docs/python/datastore/keyclass#Key_id
        """
        model_class = webapp2.get_app().get_registered_model_type(modelName)
        import urllib
        json_string = urllib.unquote(self.request.body)
        values = json.loads(json_string)

        model = webapp2.get_app().converter.create_model(model_class, values)
        self.response.set_status(201)
        self.set_location_header(model)
        self.api_success(webapp2.get_app().converter.read_model(model))
开发者ID:golsby,项目名称:appengine-json-rest,代码行数:28,代码来源:handlers.py


示例2: handle_error

def handle_error(request, response, exception):
    c = {
        'exception': str(exception),
        'url': request.url,
        }

    if config.send_mail_developer is not False:
        # send email
        subject         = config.app_name + " error."
        email_body_path = "emails/error.txt"
        message         = 'This error was looking for you: ' + c['exception'] + ' from ' + c['url']

        if c['exception'] is not 'Error saving Email Log in datastore':
            template_val = {
                "app_name"  : config.app_name,
                "message"   : message,
                }

            email_body = jinja2.get_jinja2(factory=jinja2_factory, app=webapp2.get_app()).render_template(email_body_path, **template_val)
            email_url = webapp2.uri_for('taskqueue-send-email')

            for dev in config.DEVELOPERS:
                taskqueue.add(url = email_url, params={
                    'to':       dev[1],
                    'subject' : subject,
                    'body' :    email_body,
                    'sender' :  config.contact_sender,
                    })

    status_int = hasattr(exception, 'status_int') and exception.status_int or 500
    template = config.error_templates[status_int]
    t = jinja2.get_jinja2(factory=jinja2_factory, app=webapp2.get_app()).render_template(template, **c)
    logging.error(str(status_int) + " - " + str(exception))
    response.write(t)
    response.set_status(status_int)
开发者ID:acidlabs,项目名称:gae-boilerplate,代码行数:35,代码来源:basehandler.py


示例3: handle_error

def handle_error(request, response, exception):
    c = {"exception": str(exception), "url": request.url}

    if config.send_mail_developer is not False:
        # send email
        subject = config.app_name + " error."
        email_body_path = "emails/error.txt"
        message = "This error was looking for you: " + c["exception"] + " from " + c["url"]

        if c["exception"] is not "Error saving Email Log in datastore":
            template_val = {"app_name": config.app_name, "message": message}

            email_body = jinja2.get_jinja2(factory=jinja2_factory, app=webapp2.get_app()).render_template(
                email_body_path, **template_val
            )
            email_url = webapp2.uri_for("taskqueue-send-email")

            for dev in config.DEVELOPERS:
                taskqueue.add(
                    url=email_url,
                    params={"to": dev[1], "subject": subject, "body": email_body, "sender": config.contact_sender},
                )

    status_int = hasattr(exception, "status_int") and exception.status_int or 500
    template = config.error_templates[status_int]
    t = jinja2.get_jinja2(factory=jinja2_factory, app=webapp2.get_app()).render_template(template, **c)
    logging.error(str(status_int) + " - " + str(exception))
    response.write(t)
    response.set_status(status_int)
开发者ID:berndsi,项目名称:gae-boilerplate,代码行数:29,代码来源:basehandler.py


示例4: put

    def put(self, modelName, key):
        """
        Update existing model with either numeric ID=key or key()=key.
        Usage: HTTP PUT to /rest/ModelName/id_or_key with ContentType=application/json
        Input:
        {
            "property_name": property_value,
            ...
        }
        Returns:
        {
            "status": "success",
            "data": key
        }

        Where key is the passed-in parameter
        """
        model = webapp2.get_app().get_registered_model_instance(modelName, key)
        import urllib
        json_string = urllib.unquote(self.request.body)
        values = json.loads(json_string)

        model = webapp2.get_app().converter.update_model(model, values)
        self.set_location_header(model)
        self.api_success(webapp2.get_app().converter.read_model(model))
开发者ID:golsby,项目名称:appengine-json-rest,代码行数:25,代码来源:handlers.py


示例5: post

 def post(self):
     # processes mailing tasks
     sender_address = webapp2.get_app().config['APP_INFO']['NAME'] + " Support <"+webapp2.get_app().config['APP_INFO']['EMAIL_SENDER']+">"
     mail.send_mail(sender_address, 
                    self.request.get('email'), 
                    self.request.get('subject'),
                    self.request.get('body'), 
                    reply_to=webapp2.get_app().config['APP_INFO']['EMAIL_REPLY'])
开发者ID:mayk93,项目名称:College,代码行数:8,代码来源:gamecommon.py


示例6: handle_error

def handle_error(request, response, exception):
    exc_type, exc_value, exc_tb = sys.exc_info()

    c = {"exception": str(exception), "url": request.url}

    if request.app.config.get("send_mail_developer") is not False:
        # send email
        subject = "[{}] ERROR {}".format(
            request.app.config.get("environment").upper(), request.app.config.get("app_name")
        )

        lines = traceback.format_exception(exc_type, exc_value, exc_tb)

        message = (
            "<strong>Type:</strong> "
            + exc_type.__name__
            + "<br />"
            + "<strong>Description:</strong> "
            + c["exception"]
            + "<br />"
            + "<strong>URL:</strong> "
            + c["url"]
            + "<br />"
            + "<strong>Traceback:</strong> <br />"
            + "<br />".join(lines)
        )

        email_body_path = "emails/error.txt"
        if c["exception"] is not "Error saving Email Log in datastore":
            template_val = {"app_name": request.app.config.get("app_name"), "message": message}

            email_body = jinja2.get_jinja2(factory=jinja2_factory, app=webapp2.get_app()).render_template(
                email_body_path, **template_val
            )
            email_url = webapp2.uri_for("taskqueue-send-email")

            for dev in request.app.config.get("developers"):
                taskqueue.add(
                    url=email_url,
                    params={
                        "to": dev[1],
                        "subject": subject,
                        "body": email_body,
                        "sender": request.app.config.get("contact_sender"),
                    },
                )

    status_int = hasattr(exception, "status_int") and exception.status_int or 500
    template = request.app.config.get("error_templates")[status_int]
    t = jinja2.get_jinja2(factory=jinja2_factory, app=webapp2.get_app()).render_template(template, **c)
    logging.error(str(status_int) + " - " + str(exception))
    response.write(t)
    response.set_status(status_int)
开发者ID:fccoelho,项目名称:epigrassgae,代码行数:53,代码来源:basehandler.py


示例7: recoverpw

    def recoverpw(self):
        email = self.get_post('em', '')
        
        if not mail.is_email_valid(email):
            self.respond("0Please enter a valid e-mail address."); return
        
        # find the user from e-mail
        email = email.lower()
        user = User.get_by_auth_id(auth_id='own:' + email)        
        if user:
            game_name = webapp2.get_app().config['APP_INFO']['NAME']
            game_url = webapp2.get_app().config['APP_INFO']['URL']
            new_pass = security.generate_random_string(length=5)
            user.password = security.generate_password_hash(new_pass, length=12)
            try:                
                user.put()
            except:
                self.respond("0Password recovery failed. Please try again later.")
                return                

            subject = game_name + " login password recovery"
            body = """
Dear %s

This is an automated response. A request was made for your login password used with %s

Your new password is: %s

Use this new password to login to the game. You may change the password in your profile section.
For more information, visit %s

Thank you
""" % (user.name, game_name, new_pass, game_url)

            # send the email via tasqueue so this request can return now and not wait for mail api
            taskqueue.add(queue_name='prioritymail', url='/work/mailer/', params={
                        'email':email,
                        'subject':subject,
                        'body':body,
                        })
            
            if webapp2.get_app().debug:            
                self.respond("1<pre>"+body+"</pre>")
            else:
                self.respond("1")
            return
        
        else:
            self.respond("0We do not have a record of that e-mail address. You may register to join this game.")
            return
        
        self.respond("0")
开发者ID:mayk93,项目名称:College,代码行数:52,代码来源:gamecommon.py


示例8: get

 def get(self, modelName, key):
     """
     Usage: HTTP GET to /rest/ModelName/key_or_id
     Returns:
     {
         "status": "success",
         "data": {
             "property_name": property_value,
             ...
         }
     }
     """
     model = webapp2.get_app().get_registered_model_instance(modelName, key)
     self.api_success(webapp2.get_app().converter.read_model(model))
开发者ID:golsby,项目名称:appengine-json-rest,代码行数:14,代码来源:handlers.py


示例9: setUp

    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()

        # Need to set up a global application and Request instance for
        # the i18n module to work. There's probably a more elegant way
        # of doing this.
        self.request_stub = webapp2.Request.blank("/")
        self.request_stub.user = None
        self.request_stub.app = main.APPLICATION
        webapp2.WSGIApplication.app = main.APPLICATION
        webapp2.get_app().set_globals(main.APPLICATION, self.request_stub)
开发者ID:SecondLiners,项目名称:GO2,代码行数:14,代码来源:trashcan_test.py


示例10: validate_password

def validate_password( password ):
	result = enki.libutil.ENKILIB_OK
	if password == '':
		result = ERROR_PASSWORD_BLANK
	elif len( password ) < webapp2.get_app().config.get( 'enki' ).get( 'user' ).get( 'PASSWORD_LENGTH_MIN' ):
		result = ERROR_PASSWORD_TOO_SHORT
	return result
开发者ID:juliettef,项目名称:enkiWS,代码行数:7,代码来源:libuser.py


示例11: get_lgn_client

def get_lgn_client():
    '''
    Returns a soap client object.

    If an object has already been created, we recyle it,
    otherwise, a new one is created and returned.

    '''
    app = webapp2.get_app()
    request = webapp2.get_request()

    username = request.registry['session'].get('username')
    password = request.registry['session'].get('password')
    lgn_key = 'lgn_client:{}'.format(username)

    # Check if we already have the client
    lgn_client = app.registry.get(lgn_key)

    if not lgn_client:
        lgn_client = Client(LGN_URL, cache=None)
        lgn_client.add_prefix(
            'srv', "http://service.login.core.mtrak.digi.com")
        lgn_client.add_prefix(
            'vo', "http://vo.login.core.mtrak.digi.com/xsd")

        app.registry[lgn_key] = lgn_client

    lgn_client.set_options(soapheaders=(
        Element('username').setText(username),
        Element('password').setText(password)))

    return lgn_client
开发者ID:digidotcom,项目名称:map-idigi,代码行数:32,代码来源:lgn_client.py


示例12: get_territory_mapper

def get_territory_mapper():
    app = webapp2.get_app()
    territory_mapper = app.registry.get('conquest.territory_mapper')
    if not territory_mapper:
        territory_mapper = TerritoryMapper()
        app.registry['conquest.territory_mapper'] = territory_mapper
    return territory_mapper
开发者ID:COMP3001,项目名称:Mulitplayr,代码行数:7,代码来源:models.py


示例13: hashing

def hashing(plaintext, salt="", sha="512"):
    """ Returns the hashed and encrypted hexdigest of a plaintext and salt"""
    app = webapp2.get_app()

    # Hashing
    if sha == "1":
        phrase = hashlib.sha1()
    elif sha == "256":
        phrase = hashlib.sha256()
    else:
        phrase = hashlib.sha512()
    phrase.update("%[email protected]%s" % (plaintext, salt))
    phrase_digest = phrase.hexdigest()

    # Encryption (PyCrypto)
    # wow... it's so secure :)
    try:
        from Crypto.Cipher import AES

        mode = AES.MODE_CBC

        # We can not generate random initialization vector because is difficult to retrieve them later without knowing
        # a priori the hash to match. We take 16 bytes from the hexdigest to make the vectors different for each hashed
        # plaintext.
        iv = phrase_digest[:16]
        encryptor = AES.new(app.config.get('aes_key'), mode, iv)
        ciphertext = [encryptor.encrypt(chunk) for chunk in chunks(phrase_digest, 16)]
        return ''.join(ciphertext)
    except Exception, e:
        logging.error("CRYPTO is not running: {}".format(e))
        raise
开发者ID:jcarrasko,项目名称:alf4gae,代码行数:31,代码来源:utils.py


示例14: hashing

def hashing(plaintext, salt=""):
	""" Returns the hashed and encrypted hexdigest of a plaintext and salt"""
	app = webapp2.get_app()

	# Hashing (sha512)
	plaintext = "%[email protected]%s" % (plaintext, salt)
	phrase_digest = hashlib.sha512(plaintext.encode('UTF-8')).hexdigest()

	# Encryption (PyCrypto)
	# wow... it's so secure :)
	try:
		from Crypto.Cipher import AES
		mode = AES.MODE_CBC

		# We can not generate random initialization vector because is difficult to retrieve them later without knowing
		# a priori the hash to match. We take 16 bytes from the hexdigest to make the vectors different for each hashed
		# plaintext.
		iv = phrase_digest[:16]
		encryptor = AES.new(app.config.get('aes_key'), mode,iv)
		ciphertext = [encryptor.encrypt(chunk) for chunk in chunks(phrase_digest, 16)]
		return ''.join(ciphertext)
	except (ImportError, NameError), e:
		import logging
		logging.error("CRYPTO is not running")
		return phrase_digest
开发者ID:JElbourne,项目名称:PubCart,代码行数:25,代码来源:utils.py


示例15: post

    def post(self):
        username = decode(self.request.get("username"))
        email = decode(self.request.get("email"))
        subscribe = decode(self.request.get("subscribe"))
        target_url = decode(self.request.get('continue'))
        target_url = target_url or self.uri_for('account')

        # Set a flag whether newsletter subscription setting has changed
        subscription_changed = bool(self.userprefs.subscribed_to_newsletter) \
                is not bool(subscribe)

        # Update UserPrefs object
        self.userprefs.is_setup = True
        self.userprefs.nickname = username
        self.userprefs.email = email
        self.userprefs.email_md5 = md5(email.strip().lower()).hexdigest()
        self.userprefs.subscribed_to_newsletter = bool(subscribe)
        self.userprefs.put()

        # Subscribe this user to the email newsletter now (if wanted). By
        # default does not subscribe users to mailchimp in Test Environment!
        if subscription_changed and webapp2.get_app().config.get('mailchimp')['enabled']:
            if subscribe:
                tools.mailchimp.mailchimp_subscribe(email)
            else:
                tools.mailchimp.mailchimp_unsubscribe(email)

        # After updating UserPrefs, redirect
        self.redirect(target_url)
开发者ID:scarlton,项目名称:smt,代码行数:29,代码来源:main.py


示例16: get_key_and_secret

 def get_key_and_secret(self):
     """Return tuple with Consumer Key and Consumer Secret for current
     service provider. Must return (key, secret), order *must* be respected.
     """
     app = webapp2.get_app()
     
     return app.config.get('twitter_consumer_key'), app.config.get('twitter_consumer_secret')
开发者ID:AaronHarris,项目名称:ferris-users,代码行数:7,代码来源:twitter.py


示例17: render

    def render(self, template_name, template_values={}):
        # Let's turn of GCF for those poor lost souls with IE
        self.response.headers["X-UA-Compatible"] = "chrome=1"

        # Routes common to all templates
        nav_bar = {
            "home": webapp2.uri_for("home"),
            "login": webapp2.uri_for("login"),
            "logout": webapp2.uri_for("logout"),
            "account": webapp2.uri_for("account"),
            "forum": webapp2.uri_for("forum"),
            "comprendre": webapp2.uri_for("comprendre"),
            "faq": webapp2.uri_for("faq"),
        }
        # Preset values for the template
        values = {
            "request": self.request,
            "prefs": self.userprefs,
            "login_url": users.create_login_url(self.request.uri),
            "logout_url": users.create_logout_url(self.request.uri),
            "is_testenv": tools.common.is_testenv(),
            "nav_bar": nav_bar,
        }

        # Add manually supplied template values
        values.update(template_values)

        template_dir = os.path.join(os.path.dirname(__file__), "../%s" % webapp2.get_app().config.get("template.dir"))

        # Render template
        fn = os.path.join(template_dir, template_name)
        self.response.out.write(template.render(fn, values, debug=tools.common.is_testenv()))
开发者ID:nkhine,项目名称:nimesel,代码行数:32,代码来源:baserequesthandler.py


示例18: render

    def render(self, template_name, template_values={}):
        #Let's turn of GCF for those poor lost souls with IE
        self.response.headers['X-UA-Compatible'] = 'chrome=1'

        # Routes common to all templates
        nav_bar = {
            'home':webapp2.uri_for('home'),
            'login': webapp2.uri_for('login'),
            'logout': webapp2.uri_for('logout'),
            'account': webapp2.uri_for('account')
        }
        # Preset values for the template
        values = {
          'request': self.request,
          'prefs': self.userprefs,
          'login_url': users.create_login_url(self.request.uri),
          'logout_url': users.create_logout_url(self.request.uri),
          'is_testenv':tools.common.is_testenv(),
          'nav_bar': nav_bar
        }

        # Add manually supplied template values
        values.update(template_values)

        template_dir = os.path.join(os.path.dirname(__file__),
            '../%s' % webapp2.get_app().config.get('template.dir'))

        # Render template
        fn = os.path.join(template_dir, template_name)
        self.response.out.write(template.render(fn, values,
                debug=tools.common.is_testenv()))
开发者ID:Cirrus-Business,项目名称:Cirrus-Business-clean,代码行数:31,代码来源:baserequesthandler.py


示例19: get_device_client

def get_device_client():
    '''
    Returns a soap client object.

    If an object has already been created, we recyle it,
    otherwise, a new one is created and returned.

    '''
    app = webapp2.get_app()
    request = webapp2.get_request()

    # check if we already have the client
    username = request.registry['session'].get('username')
    password = request.registry['session'].get('password')
    device_key = 'device_client:{}'.format(username)

    # check if we aleady have the client
    device_client = app.registry.get(device_key)
    if not device_client:
        device_client = Client(DEV_URL, cache=None)
        device_client.add_prefix(
            'rsp', "http://response.devicemanagement.core.mtrak.digi.com/xsd")
        device_client.add_prefix(
            'srv', "http://service.devicemanagement.core.mtrak.digi.com")
        device_client.add_prefix(
            'vo', "http://vo.devicemanagement.core.mtrak.digi.com/xsd")

        app.registry[device_key] = device_client

    device_client.set_options(soapheaders=(
        Element('username').setText(username),
        Element('password').setText(password)))

    return device_client
开发者ID:digidotcom,项目名称:map-idigi,代码行数:34,代码来源:device_client.py


示例20: member_cache_is_dirty

 def member_cache_is_dirty(self, member_key):
     app = webapp2.get_app()
     dirty_list = app.registry.get("member_dirty_cache_list")
     if not dirty_list or member_key not in dirty_list:
         return False
     else:
         return True
开发者ID:ChaoticNoise,项目名称:GO2,代码行数:7,代码来源:requestmodel.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python webapp2.get_request函数代码示例发布时间:2022-05-26
下一篇:
Python webapp2.abort函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap