Example #1
0
    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))
Example #2
0
    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))
Example #3
0
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)
Example #4
0
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)
Example #5
0
 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'])
Example #6
0
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)
Example #7
0
    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")
Example #8
0
 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))
Example #9
0
    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)
Example #10
0
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
Example #11
0
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("%s@%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(settings.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
Example #12
0
def get_fms_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")
    fms_key = "fms_client:{}".format(username)

    # check if we already have the client
    fms_client = app.registry.get(fms_key)
    if not fms_client:
        fms_client = Client(FMS_URL, cache=None)
        fms_client.add_prefix("rsp", "http://response.atms.core.mtrak.digi.com/xsd")
        fms_client.add_prefix("srv", "http://service.atms.core.mtrak.digi.com")
        fms_client.add_prefix("vo", "http://vo.atms.core.mtrak.digi.com/xsd")

        app.registry[fms_key] = fms_client

    fms_client.set_options(soapheaders=(Element("username").setText(username), Element("password").setText(password)))

    return fms_client
Example #13
0
 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')
Example #14
0
    def get(self):
        # Parse eIDs
        try:
            eIDs = [int(x) for x in (self.request.GET['eids'].split(','))]
        except:
            self.abort(
                400,
                detail='Could not parse parameter "eids" as a list of integers'
            )

        # Limit the number of eIDs in a single query
        max_count = 50
        if len(eIDs) > max_count:
            self.abort(400,
                       detail='Too many eIDs requested at once (maximum %d)' %
                       (max_count))

        # Obtain pointer to the database connection object
        db = webapp2.get_app().registry['db']

        # Carry out the API logic
        result = get_GetInfos(db, eIDs)

        # Return the result as JSON
        self.returnJSON(result)
Example #15
0
    def _add_entity_info_to_vertices(self, vertices):
        """Endows vertices with information about their entities."""

        # No work to be done if the subgraph is empty. This is necessary
        # as PostgreSQL does not handle an empty WHERE IN clause.
        if len(vertices) == 0:
            return

        db = webapp2.get_app().registry['db']
        vertices_eids = [v['eid'] for v in vertices]
        q = """
        SELECT
          entities.id AS eid,
          entities.name,
          entity_flags.trade_with_government AS trade_with_government,
          entity_flags.political_entity AS political_entity,
          entity_flags.contact_with_politics AS contact_with_politics
        FROM entities
        LEFT JOIN entity_flags ON entity_flags.eid=entities.id
        WHERE entities.id IN %s;
        """
        q_data = [tuple(vertices_eids)]
        eid_to_entity = {row['eid']: row for row in db.query(q, q_data)}
        for vertex in vertices:
            entity = eid_to_entity[vertex['eid']]
            vertex['entity_name'] = entity['name']
            for key in [
                    'trade_with_government', 'political_entity',
                    'contact_with_politics'
            ]:
                vertex[key] = entity[key]
Example #16
0
  def __init__(self):
  
    self.webapp = webapp2.get_app()
    self.webapp.rozengine = self
    
    self.enabled = True
    self.admin_enabled = True
    self.admin_path = 'admin'
    self.registerd_apps = []
    self.apps = {}
    self.models = {}
    
    self._template_path = os.path.dirname(__file__) + "/templates"
    self._registered_default_url = False

    self.template_engine = jinja2.Environment(
        loader=jinja2.FileSystemLoader(self._template_path))
        
    self.admin_template_engine = jinja2.Environment(
        loader=jinja2.FileSystemLoader(os.path.dirname(__file__) + "/templates"))
    
    self.routes = RozEngine.ROUTES   
    self.app_routes = RozApp.ROUTES
    
    self.model_routes = RozModel.ROUTES
    
    RozEngine.Engine = self
Example #17
0
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("%s@%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
Example #18
0
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
Example #19
0
 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')
Example #20
0
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
Example #21
0
def get_bitly_url(str_query):
    import urllib2
    url = url_for('frontend/link/share', _full=True) + '?' + str_query
    if get_app().debug:
        url = "http://puertogeo.appspot.com" + url_for(
            'frontend/link/share') + '?' + str_query

    shortener_params = {
        "login": "******",
        "apiKey": "R_3a5d98588cb05423c22de21292cd98d6",
        "longurl": url,
        "format": "json"
    }

    form_data = urllib.urlencode(shortener_params)

    post_url = 'http://api.bitly.com/v3/shorten?' + form_data

    result = urllib2.urlopen(post_url).read()

    bitlydata = json.decode(result)

    bitly_hash = ""
    if 'url' in bitlydata['data']:
        bitly_hash = bitlydata['data']['hash']

    return url_for('frontend/link/map', _full=True, bitly_hash=bitly_hash)
Example #22
0
 def handler(request, response, exception):
     logging.exception(exception)
     app = webapp2.get_app()
     j = jinja2.get_jinja2(app=app)
     rv = j.render_template("errors/" + str(code) + ".html")
     response.write(rv)
     response.set_status(code)
Example #23
0
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
Example #24
0
 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
Example #25
0
def hashing(plaintext, salt=""):
	""" Returns the hashed and encrypted hexdigest of a plaintext and salt"""
	app = webapp2.get_app()

	# Hashing (sha512)
	plaintext = "%s@%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
Example #26
0
    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()))
Example #27
0
 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
Example #28
0
File: main.py Project: scarlton/smt
    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)
    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()))
Example #30
0
  def post(self):
    """Request handler for POST requests."""
    logging.debug(self.request)

    # Get saved application state.
    app = webapp2.get_app()

    # Application can occasionally lose state.
    if app.registry.get('grid') is None:
      logging.warn('No board found in application.')
      logging.debug(webapp2.get_app())

      response = {self.STATUS: self.FAILED,
                  self.MESSAGE: 'Board not ready. Please refresh the page.'}
      logging.debug(response)
      self.response.write(json.dumps(response))
      return

    request = json.loads(self.request.body)

    action = request.get('action')
    player = request.get('player')
    logging.info('Action: %s Player: %s', action, player)

    if action == 'reset':
      logging.info('Reset board by player %s.', player)
      response = self.__reset_board(app)
    elif action == 'take':
      position_x = request.get('x')
      position_y = request.get('y')

      logging.info('Trying to take (%s, %s) as %s',
                   position_x,
                   position_y,
                   player)

      response = self.__take_cell(app,
                                  player,
                                  position_x,
                                  position_y)
    else:
      logging.warn('Unknown action: %s', action)
      response = {self.STATUS: self.FAILED,
                  self.MESSAGE: 'Cannot recognize action: %s' % action}

    logging.debug(response)
    self.response.write(json.dumps(response))
 def push_notification(self, to_email, subject, template, **template_val):
     if self._handler is None:
         email_body = jinja2.get_jinja2(
             factory=jinja2.Jinja2(webapp2.get_app()),
             app=webapp2.get_app()).render_template(template,
                                                    **template_val)
         email_url = webapp2.uri_for('taskqueue-send-email')
     else:
         email_body = self._handler.jinja2.render_template(
             template, **template_val)
         email_url = self._handler.uri_for('taskqueue-send-email')
     taskqueue.add(url=email_url,
                   params={
                       'to': to_email,
                       'subject': subject,
                       'body': email_body
                   })
Example #32
0
 def get(self, user_name):
     size = self.request.get("size", "200u")
     album_id = int(self.request.get("album_id", 0))
     picture = webapp2.get_app().registry["picker"].Pick(user_name, size, album_id)
     if picture:
         self.redirect(picture.GetThumbnailUrl().encode())
     else:
         self.response.set_status(204)
Example #33
0
 def get(self, modelName=None):
     if modelName:
         modelClass = webapp2.get_app().get_registered_model_type(modelName)
         metadata = webapp2.get_app().converter.metadata(modelClass)
         self.api_success(metadata)
     else:
         models = webapp2.get_app().get_registered_model_names()
         data = []
         for model in models:
             data.append(
                 {
                     'name': model,
                     'url': '{0}{1}'.format(self.request.host_url, webapp2.get_app().model_url(model)),
                     'metadata_url': '{0}/metadata'.format(webapp2.get_app().model_url(model))
                 }
             )
         self.api_success(data)
Example #34
0
 def get(self, challenge):
     app = webapp2.get_app()
     response = app.registry.get(challenge)
     if not response:
       self.response.set_status(404)
       return
     self.response.headers['Content-Type'] = 'text/plain'
     self.response.write(response)
Example #35
0
 def member_cache_set_clean(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
     else:
         dirty_list.remove(member_key)
         app.registry['member_dirty_cache_list'] = dirty_list
Example #36
0
 def set_member_cache_dirty(self, member_key):
     app = webapp2.get_app()
     dirty_list = app.registry.get("member_dirty_cache_list")
     if not dirty_list:
         dirty_list = []
     if not member_key in dirty_list:
         dirty_list.append(member_key)
     app.registry["member_dirty_cache_list"] = dirty_list
Example #37
0
def handle_error(request, response, exception):
    c = { 'exception': str(exception) }
    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)
Example #38
0
 def member_cache_set_clean(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
     else:
         dirty_list.remove(member_key)
         app.registry["member_dirty_cache_list"] = dirty_list
Example #39
0
 def set_member_cache_dirty(self,member_key):
     app = webapp2.get_app()
     dirty_list = app.registry.get('member_dirty_cache_list')
     if not dirty_list:
         dirty_list = []
     if not member_key in dirty_list:
         dirty_list.append(member_key)
     app.registry['member_dirty_cache_list'] = dirty_list
Example #40
0
def route_name_exists(name, *args, **kwargs):
    """
    Checks if a particlar named route (i.e. 'entries-list') exists.
    """
    route = webapp2.get_app().router.build_routes.get(name)
    if route == None:
        return False
    return True
Example #41
0
 def __init__(self, request, response):
     # Set self.request, self.response and self.app.
     self.initialize(request, response)
     app = webapp2.get_app()
     app.registry['preflightrequest'] = self.request
     print "preflight app.registry is", app.registry
     print app.registry[
         'preflightrequest']  #Levi I don't know why, but without this, complains about expired request
def route_name_exists(name, *args, **kwargs):
    """
    Checks if a particlar named route (i.e. 'entries-list') exists.
    """
    route = webapp2.get_app().router.build_routes.get(name)
    if route == None:
        return False
    return True
Example #43
0
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)
        ua = httpagentparser.detect(request.user_agent)
        _os = ua.has_key('flavor') and 'flavor' or 'os'

        operating_system = str(ua[_os]['name']) if "name" in ua[_os] else "-"
        if 'version' in ua[_os]:
            operating_system += ' ' + str(ua[_os]['version'])
        if 'dist' in ua:
            operating_system += ' ' + str(ua['dist'])

        browser = str(ua['browser']['name']) if 'browser' in ua else "-"
        browser_version = str(ua['browser']['version']) if 'browser' in ua else "-"

        message = '<strong>Application ID:</strong> ' + app_identity.get_application_id() + "<br />" + \
                  '<strong>Application Version:</strong> ' + os.environ['CURRENT_VERSION_ID'] + "<br />" + \
                  '<hr><strong>User Agent:</strong> ' + str(request.user_agent) + "<br />" + \
                  '<strong>IP Address:</strong> ' + str(request.remote_addr) + "<br />" + \
                  '<strong>Operating System:</strong> ' + str(operating_system) + "<br />" + \
                  '<strong>Browser:</strong> ' + str(browser) + "<br />" + \
                  '<strong>Browser Version:</strong> ' + str(browser_version) + "<br />" + \
                  '<hr><strong>Error Type:</strong> ' + exc_type.__name__ + "<br />" + \
                  '<strong>Description:</strong> ' + c['exception'] + "<br />" + \
                  '<strong>Method:</strong> ' + str(os.environ['REQUEST_METHOD']) + "<br />" + \
                  '<strong>URL:</strong> ' + c['url'] + "<br />" + \
                  '<strong>Referer:</strong> ' + str(request.referer) + "<br />" + \
                  '<strong>Traceback:</strong> <br />' + '<br />'.join(lines)

        if c['exception'] is not 'Error saving Email Log in datastore':
            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': message,
                    '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(app=webapp2.get_app()).render_template(template, **c)
    logging.error("Error {}: {}".format(status_int, exception))
    response.write(t)
    response.set_status(status_int)
Example #44
0
 def get(self):
     try:
         start = [int(x) for x in (self.request.GET['eid'].split(','))[:50]]
         cap = int(self.request.GET['cap'])
     except:
         self.abort(400, detail='Could not parse parameters')
     relations_old = webapp2.get_app().registry['relations_old']
     response = relations_old.dijkstra(start, [], cap=cap, return_all=True)
     self.returnJSON(response)
Example #45
0
    def __init__(self, *args, **kw):
        super(User, self).__init__(*args, **kw)
        if 'name' not in self:
            raise ValueError('Missing user name')

        self.name = self['name']
        self.domain = self.get('domain')
        self.is_boss = (gooser.is_current_user_admin() or self.__repr__()
                        in webapp2.get_app().config['bosses'])
Example #46
0
def get_current_user():
    """  GAE compatibility method. """
    request = webapp2.get_request()
    app = webapp2.get_app()
    audience = app.config.get('idtoken_audience')
    if not audience:
        raise Exception('idtoken_audience not configured')
    token = request.headers.get('x-w69b-idtoken')
    return _user_from_token(token, audience)
Example #47
0
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_mail_stub()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()
        self.mail_stub = self.testbed.get_stub(testbed.MAIL_SERVICE_NAME)

        crypto_db.set_cryptokey('dead0000dead0000')

        # 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)
Example #48
0
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)
def offline_update_data_handler(request, *args, **kwargs):
    app = webapp2.get_app()
    data = {
        'vendor': request.POST['vendor'],
        'encrypted_payload': request.POST['encrypted_payload'],
        'endpoint': request.POST['endpoint'],
    }
    app.registry[OFFLINE_REGISTRY_KEY] = data
    return webapp2.Response().set_status(
        200, "Successfully saved Offline Payment data.")
Example #50
0
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)
Example #51
0
 def get(self):
   db = webapp2.get_app().registry['db']
   rows = db.query(
       """
       SELECT
         eid,
         e1.name,
         supplier_eid,
         e2.name as supplier_name,
         Notices.notice_id,
         contract_id,
         title,
         estimated_value_amount,
         estimated_value_currency,
         Notices.bulletin_issue_id,
         year as bulletin_year,
         number as bulletin_number,
         to_char(published_on,'DD.MM.YYYY') as bulletin_published_on,
         source_url as bulletin_source_url,
         notice_type_id,
         total_final_value_amount,
         total_final_value_currency,
         best_supplier,
         e3.name as best_supplier_name,
         best_similarity,
         price_est,
         price_est_low,
         price_est_high
       FROM
         Notices
       JOIN
         NoticesExtras
       ON
         Notices.notice_id = NoticesExtras.notice_id
       JOIN
         NoticeBulletins
       ON
         Notices.bulletin_issue_id = NoticeBulletins.bulletin_id
       JOIN
         Entities as e1
       ON
         e1.id = Notices.eid
       LEFT JOIN
         Entities as e2
       ON
         e2.id = Notices.supplier_eid
       LEFT JOIN
         Entities as e3
       ON
         e3.id = NoticesExtras.best_supplier
       ORDER BY
         bulletin_issue_id DESC
       LIMIT 300;
       """)
   self.returnJSON(rows)
Example #52
0
def _get_screenshots(request):
  # For speed this caches the most recent set of screenshot descriptions.
  app = webapp2.get_app()
  screenshot_source = urllib.unquote(request.get('screenshot_source'))
  old_screenshot_source = app.config.get('screenshot_source')
  if screenshot_source != old_screenshot_source:
    app.config['screenshot_source'] = screenshot_source
    screenshot_loader = app.config.get('screenshot_loader')
    app.config['screenshots'] = list(enumerate(screenshot_loader.get_data(
        screenshot_source)))
  return app.config.get('screenshots', [])
Example #53
0
 def save(cls):
     app = webapp2.get_app()
     with app.registry.get("settings_lock"):
         instance = cls.get_by_id("instance")
         settings = app.registry.get("settings")
         instance.populate(
             emails=repr(settings["emails"]),
             languages=repr(settings["languages"]),
             modalities=repr(settings["modalities"]),
             payments=repr(settings["payments"]),
         )
         instance.put()
Example #54
0
    def get(self):
        # Parse politician id
        try:
            politician_id = int(self.request.GET['id'])
        except:
            self.abort(400, detail='Could not parse parameter `id` as int')

        # Find asset declarations of this politician in the database
        db_profil = webapp2.get_app().registry['db']
        declarations = db_search.get_asset_declarations(
            db_profil, politician_id)
        self.returnJSON(declarations)
Example #55
0
    def get(self):
        try:
            eid = int(self.request.GET["eid"])
        except:
            self.abort(400,
                       detail="Could not parse parameter 'eid' as an integer")

        if eid < 0:
            self.abort(400, detail="Provided 'eid' is not an entity id")

        entities = webapp2.get_app().registry['entities']
        self.returnJSON(entities.getRelated(eid))
Example #56
0
    def get(self):
        # Parse politician id
        try:
            politician_id = int(self.request.GET['id'])
        except:
            self.abort(400, detail='Could not parse parameter `id` as int')

        # Find Parcels owned by this politician in the database
        db_profil = webapp2.get_app().registry['db']
        folios_uses = db_search.get_folios_uses_of_person(
            db_profil, politician_id)
        self.returnJSON(folios_uses)
def update_sagepay_data_handler(request, *args, **kwargs):
    app = webapp2.get_app()
    data = {
        'vpsprotocol': request.POST['vpsprotocol'],
        'txtype': request.POST['txtype'],
        'vendor': request.POST['vendor'],
        'crypt': request.POST['crypt'],
        'endpoint': request.POST['endpoint'],
    }
    app.registry[REGISTRY_KEY] = data
    return webapp2.Response().set_status(200,
                                         "Successfully saved SagePay data.")
Example #58
0
    def __init__(self, data_source_model, query):
        app = webapp2.get_app()
        bigquery_client = app.registry.get('bigquery_client')
        if not bigquery_client:
            from google.cloud import bigquery
            bigquery_client = bigquery.Client()
            app.registry['bigquery_client'] = bigquery_client

        self.bigquery_client = bigquery_client

        self.data_source_model = data_source_model
        self.query = query