コード例 #1
0
    def create_event(self, req):
        '''
        Creates a new event.

        Validates the request object, extracts all required information, and
        builds the event and associated objects.
        '''
        # TODO year mechanism.
        try:
            inputErrors = self.__eventValidator.validate_event(req.json_body)
            response_body = {}
            if not inputErrors:
                # set the creator_id and save the event
                req.json_body['creator_id'] = req.cookies['user_id']
                data = self.__event_dao.save_event(req.json_body)

                # build the response body
                response_body = json.dumps(data)

            else:
                response_body = json.dumps(inputErrors)

            response = Response(content_type='application/json', status=200)
            response.charset = 'UTF-8'
            response.json_body = response_body

        except BaseAppException as e:
            raise ServiceException(str(e))

        except Exception as e:
            print(e, sys.exc_info())
            raise ServiceException(
                'An error occurred while creating this event.')

        return response
コード例 #2
0
ファイル: attendee_service.py プロジェクト: Mac-lp3/ufree
    def load_event_attendees (self, req):
        '''
        Returns a JSON list of all attendees in this event
        '''
        try:
            # validate the event id
            eventId = req.matchdict['eventId']
            self.__eventValidator.validate_event_id(eventId)

            # load the attendee list
            data = self.__attendee_dao.load_event_attendees(eventId)

            # build response object
            response = Response(content_type='application/json', status=200)
            response.charset = 'UTF-8'
            response.json_body = json.dumps(data)

        except BaseAppException as e:
            # Handle DAO/Validation errors
            raise ServiceException(str(e))
        except Exception as e:
            # Handle unexpected errors
            print(e, sys.exc_info())
            raise ServiceException(
                'An error occurred while retrieving attendee list.'
            )

        return response
コード例 #3
0
ファイル: AriApi.py プロジェクト: SmarterApp/ARI_Prototype
def getItem(context, request):

    response = Response(content_type='application/json')

    json_files = [
        '/q1/item.json', '/q2/item.json', '/q3/item.json', '/q4/item.json',
        '/q5/item.json'
    ]

    try:
        # get cookies
        cookieval = request.cookies['signed_cookie']
        cookies = signed_deserialize(cookieval, 'secret')
        count = cookies['c']

        # set next one
        next_count = count + 1
        cookieval = signed_serialize({'c': next_count}, 'secret')
        response.set_cookie('signed_cookie', cookieval)

    except KeyError:
        cookieval = signed_serialize({'c': 0}, 'secret')
        response.set_cookie('signed_cookie', cookieval)
        count = 0

    json_file = item_path + json_files[count]

    with open(json_file, 'r') as myfile:
        json_data = myfile.read()

    response.charset = 'utf8'
    response.text = json_data
    return response
コード例 #4
0
ファイル: attendee_service.py プロジェクト: Mac-lp3/ufree
    def load_attendee (self, req):
        '''
        returns JSON data of this single attendee
        '''
        try:
            # validate
            att_id = req.matchdict['attendee_id']
            if att_id is None:
                raise ServiceException('Id was not found on this request')

            self.__attendeeValidator.validate_attendee_id(
                att_id
            )
            data = self.__attendee_dao.load_attendee(att_id)
            response = Response(content_type='application/json', status=200)
            response.charset = 'UTF-8'
            response.json_body = json.dumps(data)
        except BaseAppException as e:
            raise ServiceException(str(e))
        except Exception as e:
            print(e, sys.exc_info())
            raise ServiceException(
                'An error occurred while loading attendee with id',
                att_id
            )
        return response
コード例 #5
0
ファイル: attendee_service.py プロジェクト: Mac-lp3/ufree
    def create_attendee (self, req):
        '''
        Create and attendee and join the target event.
        '''
        try:
            # validate event ID and attendee payload
            eventId = req.matchdict['eventId']
            self.__eventValidator.validate_event_id(eventId)
            self.__attendeeValidator.validate_attendee_request(req)

            # create the attendee and join the event
            data = self.__attendee_dao.save_attendee(req.json_body)
            self.__attendee_dao.join_event(data['id'], eventId)

            # build the response body
            response = Response(content_type='application/json', status=200)
            response.charset = 'UTF-8'
            response.json_body = json.dumps(data)

        except BaseAppException as e:
            raise ServiceException(str(e))

        except Exception as e:
            print(e, sys.exc_info())
            raise ServiceException('An error occurred while creating this event.')

        return response
コード例 #6
0
 def __call__(self):
     response = Response()
     response.content_disposition = 'attachment; filename="{}"'.format(self.context.filename)
     response.charset = 'utf-8'
     response.content_type = self.context.content_type
     response.body_file = self.context.content.open()
     response.content_length = self.context.size
     return response
コード例 #7
0
def employees(request):
    logger.info("Querying SQLite database for list of employees ...")
    res = request.dbsession.query(models.Employee).all()
    response = Response(json.dumps({"employees": res}))
    response.status = "200 OK"
    response.status_int = 200
    response.content_type = "application/json"
    response.charset = "utf-8"
    return response
コード例 #8
0
def view_export_locations(request):
    contents = ""
    for location in DBSession.query(ShippingLocation).all():
        contents += location.name + ';' + location.address + '\n'

    resp = Response()
    resp.charset = "utf-8"
    resp.text = contents
    resp.headerlist.append(("Content-Disposition", "attachment"))
    return resp
コード例 #9
0
ファイル: __init__.py プロジェクト: yeastgenome/SGDFrontend
def return_plain_data(content):

    response = Response(content_type='application/html')
    headers = response.headers
    if not response.charset:
        response.charset = 'utf8'
    response.text = content
    headers['Content-Type'] = 'text/plain'

    return response
コード例 #10
0
def check_likecoin_connect_status(request):
    likecoin_id = request.matchdict['likecoin_id']
    user = UserQuery(DBSession).query.filter(
        User.like_coin_id == likecoin_id).one_or_none()

    response = Response()
    response.charset = 'UTF-8'
    response.status_code = 200
    response.text = 'OK' if user else 'NOT FOUND'
    return response
コード例 #11
0
ファイル: __init__.py プロジェクト: Soheila-Git/SGDFrontend
def return_plain_data(content):

    response = Response(content_type='application/html')
    headers = response.headers
    if not response.charset:
        response.charset = 'utf8'
    response.text = content
    headers['Content-Type'] = 'text/plain'

    return response
コード例 #12
0
ファイル: views.py プロジェクト: mushroom2/pyramid-parser
def json_view(request):
    if 'priceto' in request.cookies and 'pricefrom' in request.cookies:
        cat = request.cookies['cat']
        priceto = request.cookies['priceto']
        pricefrom = request.cookies['pricefrom']
        pars = Parser(pricefrom, priceto, cat)
        r = Response()
        r.content_type = 'application/json'
        r.charset = 'utf8'
        return pars.result
コード例 #13
0
ファイル: views.py プロジェクト: uralbash/pyramid_elfinder
def connector(request):
    # init connector and pass options
    root = request.registry.settings['pyramid_elfinder_root']
    options = {
        'root': os.path.abspath(root),
        'URL': request.registry.settings['pyramid_elfinder_url']
    }
    elf = elfinder.connector(options)

    # fetch only needed GET/POST parameters
    httpRequest = {}
    form = request.params
    for field in elf.httpAllowedParameters:
        if field in form:
            # Russian file names hack
            if field == 'name':
                httpRequest[field] = form.getone(field).encode('utf-8')

            elif field == 'targets[]':
                httpRequest[field] = form.getall(field)

            # handle CGI upload
            elif field == 'upload[]':
                upFiles = {}
                cgiUploadFiles = form.getall(field)
                for up in cgiUploadFiles:
                    if isinstance(up, FieldStorage):
                        # pack dict(filename: filedescriptor)
                        upFiles[up.filename.encode('utf-8')] = up.file
                httpRequest[field] = upFiles
            else:
                httpRequest[field] = form.getone(field)

    # run connector with parameters
    status, header, response = elf.run(httpRequest)

    # get connector output and print it out
    result = Response(status=status)
    try:
        del header['Connection']
    except Exception:
        pass
    result.headers = header
    result.charset = 'utf8'

    if response is not None and status == 200:
        # send file
        if 'file' in response and hasattr(response['file'], 'read'):
            result.body = response['file'].read()
            response['file'].close()
        # output json
        else:
            result.text = json.dumps(response)
    return result
コード例 #14
0
def connector(request):
    # init connector and pass options
    root = request.registry.settings['pyramid_elfinder_root']
    options = {
        'root': os.path.abspath(root),
        'URL': request.registry.settings['pyramid_elfinder_url']
    }
    elf = elfinder.connector(options)

    # fetch only needed GET/POST parameters
    httpRequest = {}
    form = request.params
    for field in elf.httpAllowedParameters:
        if field in form:
            # Russian file names hack
            if field == 'name':
                httpRequest[field] = form.getone(field).encode('utf-8')

            elif field == 'targets[]':
                httpRequest[field] = form.getall(field)

            # handle CGI upload
            elif field == 'upload[]':
                upFiles = {}
                cgiUploadFiles = form.getall(field)
                for up in cgiUploadFiles:
                    if isinstance(up, FieldStorage):
                        # pack dict(filename: filedescriptor)
                        upFiles[up.filename.encode('utf-8')] = up.file
                httpRequest[field] = upFiles
            else:
                httpRequest[field] = form.getone(field)

    # run connector with parameters
    status, header, response = elf.run(httpRequest)

    # get connector output and print it out
    result = Response(status=status)
    try:
        del header['Connection']
    except Exception:
        pass
    result.headers = header
    result.charset = 'utf8'

    if response is not None and status == 200:
        # send file
        if 'file' in response and hasattr(response['file'], 'read'):
            result.body = response['file'].read()
            response['file'].close()
        # output json
        else:
            result.text = json.dumps(response)
    return result
コード例 #15
0
ファイル: __init__.py プロジェクト: yeastgenome/SGDFrontend
def set_download_file(filename, content):
    
    response = Response(content_type='application/file')
    headers = response.headers
    if not response.charset:
        response.charset = 'utf8'
    response.text = content
    headers['Content-Type'] = 'text/plain'
    headers['Content-Disposition'] = str('attachment; filename=' + '"' + filename + '"')
    headers['Content-Description'] = 'File Transfer'
    return response
コード例 #16
0
ファイル: __init__.py プロジェクト: Soheila-Git/SGDFrontend
def set_download_file(filename, content):

    response = Response(content_type='application/file')
    headers = response.headers
    if not response.charset:
        response.charset = 'utf8'
    response.text = content
    headers['Content-Type'] = 'text/plain'
    headers['Content-Disposition'] = str('attachment; filename=' + '"' +
                                         filename + '"')
    headers['Content-Description'] = 'File Transfer'
    return response
コード例 #17
0
ファイル: views.py プロジェクト: tty72/qemu-tubes
 def export(self):
     exch = Exchange(Base.metadata, 
                     ignlist=['cpu_types', 'machine_types', 'nic_types'])
     fp = StringIO.StringIO()
     exch.export_xml()
     exch.write_xml(fp)
     resp = Response()
     resp.headerlist=[('Content-Type', 'text/html; charset=UTF-8'),]
     resp.text=fp.getvalue()
     resp.content_disposition = 'attachment; filename="qtubes_export.xml"'
     resp.charset='utf-8'
     return resp
コード例 #18
0
def test_response_properties():
    root_response = Response(headers={"X-Some-Special-Header": "foobar"},
                             body='{"myKey": 42}')
    # these must be set for the "text" attribute of webob.Response to be
    # readable, and setting them in the constructor gets into a conflict
    # with the custom header argument
    root_response.content_type = "application/json"
    root_response.charset = 'utf8'
    response = PyramidSwaggerResponse(root_response)
    assert '{"myKey": 42}' == response.text
    assert "foobar" == response.headers["X-Some-Special-Header"]
    assert 'application/json' == response.content_type
コード例 #19
0
ファイル: simple.py プロジェクト: ldgeo/papaye
 def __call__(self):
     check_update = True if self.request.GET.get('check_update', 'true') == 'true' else False
     package = self.context.__parent__.__parent__
     last_remote_version = Package.get_last_remote_version(self.proxy, package.name)
     if check_update:
         if not package.repository_is_up_to_date(last_remote_version):
             return not_found(self.request)
     response = Response()
     response.content_disposition = 'attachment; filename="{}"'.format(self.context.filename)
     response.charset = 'utf-8'
     response.content_type = self.context.content_type
     response.body_file = self.context.content.open()
     return response
コード例 #20
0
def generate_template(templateName, data):
    resp = Response(
        render(
            '/var/www/conference_abstract/conference_abstract/templates/' +
            templateName, data))
    #respTemplate = ('/var/www/conference_abstract/conference_abstract/templates/'+templateName)
    #print respTemplate.render_unicode(template_args=data)

    resp.headerlist.append(('Access-Control-Allow-Origin', '*'))
    resp.content_type = 'text/html; charset=utf-8'
    resp.charset = "utf-8"

    return resp
コード例 #21
0
def set_download_file(alignment, type):

    lines = alignment.split("\n")

    ref_id = None
    ref_seq = None
    id2seq = {}

    newLines = []
    for line in lines:
        if line == '' or "CLUSTAL" in line:
            continue
        while '  ' in line:
            line = line.replace('  ', ' ')
        pieces = line.split(" ")
        if len(pieces) != 2:
            continue
        id = pieces[0]
        if id == '':
            continue
        seq = pieces[1]
        if 'S288C' in id:
            ref_id = id
            if ref_seq is None:
                ref_seq = seq
            else:
                ref_seq = ref_seq + seq
        else:
            if id in id2seq:
                id2seq[id] = id2seq[id] + seq
            else:
                id2seq[id] = seq

    content = ">" + ref_id + "\n" + format_fasta(ref_seq.replace("-",
                                                                 "")) + "\n"
    for id in sorted(id2seq.keys()):
        content = content + ">" + id + "\n" + format_fasta(id2seq[id].replace(
            "-", "")) + "\n"

    filename = ref_id.split("_")[0] + "_" + type + ".fsa"

    response = Response(content_type='application/file')
    headers = response.headers
    if not response.charset:
        response.charset = 'utf8'
    response.text = str(content)
    headers['Content-Type'] = 'text/plain'
    headers['Content-Disposition'] = str('attachment; filename=' + '"' +
                                         filename + '"')
    headers['Content-Description'] = 'File Transfer'
    return response
コード例 #22
0
    def export(self, extm, params, req):
        csv_dialect = params.pop('csv_dialect', 'excel')
        csv_encoding = params.pop('csv_encoding', 'utf_8')
        fields = []
        for field in extm.export_view:
            if isinstance(field, PseudoColumn):
                continue
            fields.append(field)

        if csv_encoding not in csv_encodings:
            raise ValueError('Unknown encoding specified')
        res = Response()
        loc = req.localizer
        now = datetime.datetime.now()
        res.last_modified = now
        if csv_dialect in ('excel', 'excel-tab'):
            res.content_type = 'application/vnd.ms-excel'
        else:
            res.content_type = 'text/csv'
        res.charset = csv_encodings[csv_encoding][0]
        res.cache_control.no_cache = True
        res.cache_control.no_store = True
        res.cache_control.private = True
        res.cache_control.must_revalidate = True
        res.headerlist.append(('X-Frame-Options', 'SAMEORIGIN'))
        if PY3:
            res.content_disposition = \
             'attachment; filename*=UTF-8\'\'%s-%s.csv' % (
              urllib.parse.quote(loc.translate(extm.menu_name), ''),
              now.date().isoformat()
             )
        else:
            res.content_disposition = \
             'attachment; filename*=UTF-8\'\'%s-%s.csv' % (
              urllib.quote(loc.translate(extm.menu_name).encode(), ''),
              now.date().isoformat()
             )

        for prop in ('__page', '__start', '__limit'):
            if prop in params:
                del params[prop]
        data = extm.read(params, req)['records']

        res.app_iter = csv_generator(data,
                                     fields,
                                     csv_dialect,
                                     encoding=csv_encoding,
                                     localizer=loc,
                                     model=extm)
        return res
コード例 #23
0
ファイル: csv.py プロジェクト: hermes-jr/npui
	def export(self, extm, params, req):
		csv_dialect = params.pop('csv_dialect', 'excel')
		csv_encoding = params.pop('csv_encoding', 'utf_8')
		fields = []
		for field in extm.export_view:
			if isinstance(field, PseudoColumn):
				continue
			fields.append(field)

		if csv_encoding not in _encodings:
			raise ValueError('Unknown encoding specified')
		res = Response()
		loc = get_localizer(req)
		now = datetime.datetime.now()
		res.last_modified = now
		if csv_dialect in ('excel', 'excel-tab'):
			res.content_type = 'application/vnd.ms-excel'
		else:
			res.content_type = 'text/csv'
		res.charset = _encodings[csv_encoding][0]
		res.cache_control.no_cache = True
		res.cache_control.no_store = True
		res.cache_control.private = True
		res.cache_control.must_revalidate = True
		res.headerlist.append(('X-Frame-Options', 'SAMEORIGIN'))
		if PY3:
			res.content_disposition = \
				'attachment; filename*=UTF-8\'\'%s-%s.csv' % (
					urllib.parse.quote(loc.translate(extm.menu_name), ''),
					now.date().isoformat()
				)
		else:
			res.content_disposition = \
				'attachment; filename*=UTF-8\'\'%s-%s.csv' % (
					urllib.quote(loc.translate(extm.menu_name).encode(), ''),
					now.date().isoformat()
				)

		for prop in ('__page', '__start', '__limit'):
			if prop in params:
				del params[prop]
		data = extm.read(params, req)['records']

		res.app_iter = csv_generator(
			data, fields, csv_dialect,
			encoding=csv_encoding,
			localizer=loc,
			model=extm
		)
		return res
コード例 #24
0
ファイル: tween_test.py プロジェクト: ATRAN2/pyramid_swagger
def test_response_properties():
    root_response = Response(
        headers={"X-Some-Special-Header": "foobar"},
        body='{"myKey": 42}'
    )
    # these must be set for the "text" attribute of webob.Response to be
    # readable, and setting them in the constructor gets into a conflict
    # with the custom header argument
    root_response.content_type = "application/json"
    root_response.charset = 'utf8'
    response = PyramidSwaggerResponse(root_response)
    assert '{"myKey": 42}' == response.text
    assert "foobar" == response.headers["X-Some-Special-Header"]
    assert 'application/json' == response.content_type
コード例 #25
0
def view_export_products(request):
    contents = ""
    for product in DBSession.query(Product).all():
        contents += product.handle + ';' + product.type + ';' + product.subtype + ';' + str(product.maara_per_lavametri) + ';' + str(product.km_raja)
        for location in product.locations:
            contents += ';' + str(location.name)
        contents += '\n'
#            ';'.join(product.locations) + '\n'

    resp = Response()
    resp.charset = "utf-8"
    resp.text = contents
    resp.headerlist.append(("Content-Disposition", "attachment"))
    return resp
コード例 #26
0
 def update_event(self, req):
     try:
         payload = req.json_body
         self.__eventValidator.validate_event(payload)
         data = self.__event_dao.update_event(payload)
         response = Response(content_type='application/json', status=200)
         response.charset = 'UTF-8'
         response.json_body = json.dumps(data)
     except BaseAppException as e:
         raise ServiceException(str(e))
     except Exception as e:
         print(e, sys.exc_info())
         raise ServiceException(
             'An error occurred while updating this event.')
     return response
コード例 #27
0
ファイル: __init__.py プロジェクト: yeastgenome/SGDFrontend
def set_download_file(alignment, type):

    lines = alignment.split("\n")

    ref_id = None
    ref_seq = None
    id2seq = {}

    newLines = []
    for line in lines:
        if line == '' or "CLUSTAL" in line:
            continue
        while '  ' in line:
            line = line.replace('  ', ' ')
        pieces = line.split(" ")
        if len(pieces) != 2:
            continue
        id = pieces[0]
        if id == '':
            continue
        seq = pieces[1]
        if 'S288C' in id:
            ref_id = id
            if ref_seq is None:
                ref_seq = seq
            else:
                ref_seq = ref_seq + seq
        else:
            if id in id2seq:
                id2seq[id] = id2seq[id] + seq
            else:
                id2seq[id] = seq
                
    content = ">" + ref_id + "\n" + format_fasta(ref_seq.replace("-", "")) + "\n"
    for id in sorted(id2seq. iterkeys()):
        content = content + ">" + id + "\n" + format_fasta(id2seq[id].replace("-", "")) + "\n"

    filename = ref_id.split("_")[0] + "_" + type + ".fsa" 
    
    response = Response(content_type='application/file')
    headers = response.headers
    if not response.charset:
        response.charset = 'utf8'
    response.text = unicode(content)
    headers['Content-Type'] = 'text/plain'
    headers['Content-Disposition'] = str('attachment; filename=' + '"' + filename + '"')
    headers['Content-Description'] = 'File Transfer'
    return response
コード例 #28
0
    def delete_event_availability(self, req):
        try:
            event_id = req.matchdict['eventId']
            self.__event_validator.validate_event_id(event_id)

            self.__availability_dao.delete_event_availability(event_id)
            response = Response(content_type='application/json', status=200)
            response.charset = 'UTF-8'
        except BaseAppException as e:
            raise ServiceException(str(e))
        except Exception as e:
            print(e, sys.exc_info())
            raise ServiceException(
                'An error occurred while deleting availability for event:',
                event_id)
        return response
コード例 #29
0
ファイル: simple.py プロジェクト: pombredanne/papaye
 def __call__(self):
     check_update = True if self.request.GET.get(
         'check_update', 'true') == 'true' else False
     package = self.context.__parent__.__parent__
     last_remote_version = Package.get_last_remote_version(
         self.proxy, package.name)
     if check_update:
         if not package.repository_is_up_to_date(last_remote_version):
             return not_found(self.request)
     response = Response()
     response.content_disposition = 'attachment; filename="{}"'.format(
         self.context.filename)
     response.charset = 'utf-8'
     response.content_type = self.context.content_type
     response.body_file = self.context.content.open()
     response.content_length = self.context.size
     return response
コード例 #30
0
    def get_availability(self, req):
        try:
            availability_id = req.matchdict['availabilityId']
            self.__availability_validator.validate_availability_id(
                availability_id)
            data = self.__availability_dao.get_availability(availability_id)
            response = Response(content_type='application/json', status=200)
            response.charset = 'UTF-8'
            response.json_body = json.dumps(data)
        except BaseAppException as e:
            raise ServiceException(str(e))
        except Exception as e:
            print(e, sys.exc_info())
            raise ServiceException(
                'An error occurred while loading availability with id:',
                availability_id)

        return response
コード例 #31
0
ファイル: models.py プロジェクト: mmariani/pyramid_skins
    def __call__(self, context=None, request=None, **kw):
        if self.path is None:
            inst = self.__get__()
            return inst(context=context, request=request, **kw)

        result = self.render(context=context, request=request, **kw)
        if isinstance(result, basestring):
            response = Response(body=result)
        else:
            response = Response(app_iter=result)
            response.content_length = os.path.getsize(self.path)

        content_type = self.content_type
        if content_type is None:
            content_type = type(self).content_type
        response.content_type = content_type
        response.charset = self.encoding
        return response
コード例 #32
0
    def update_availability(self, req):
        try:
            # validate the payload
            self.__availability_validator.vaildaite_availability_request(req)

            # set the creator_id and save the event
            data = self.__availability_dao.update_availability(req.json_body)

            # build the response body
            response_body = json.dumps(data)
            response = Response(content_type='application/json', status=200)
            response.charset = 'UTF-8'
            response.json_body = response_body
            return response

        except BaseAppException as e:
            raise ServiceException(str(e))

        except Exception as e:
            print(e, sys.exc_info())
            raise ServiceException(
                'An error occurred while updating this event.')
コード例 #33
0
ファイル: attendee_service.py プロジェクト: Mac-lp3/ufree
 def update_attendee_availability (self, req):
     '''
     TODO ?
     Updates the availability of an attendee
     '''
     try:
         # TODO validate availability
         self.__attendeeValidator.validate_attendee_request(req)
         data = self.__availability_dao.update_availability(req.json_body)
         response = Response(content_type='application/json', status=200)
         response.charset = 'UTF-8'
         response.json_body = json.dumps(data)
     except BaseAppException as e:
         # Handle DAO/Validation errors
         raise ServiceException(str(e))
     except Exception as e:
         # Handle unexpected errors
         print(e, sys.exc_info())
         raise ServiceException(
             'An error occurred while updating availability.'
         )
     return response
コード例 #34
0
    def __call__(self, context=None, request=None, **kw):
        if request is None:
            request = get_current_request()
        if self.path is None:
            registry = request.registry
            inst = registry.queryAdapter(request, ISkinObject, name=self.name)
            if inst is None:
                inst = registry.getUtility(ISkinObject, name=self.name)
            return inst(context=context, request=request, **kw)

        result = self.render(context=context, request=request, **kw)
        if isinstance(result, string_types):
            response = Response(body=result)
        else:
            response = Response(app_iter=result)
            response.content_length = os.path.getsize(self.path)

        content_type = self.content_type
        if content_type is None:
            content_type = type(self).content_type
        response.content_type = content_type
        response.charset = self.encoding
        return response
コード例 #35
0
ファイル: models.py プロジェクト: Pylons/pyramid_skins
    def __call__(self, context=None, request=None, **kw):
        if request is None:
            request = get_current_request()
        if self.path is None:
            registry = request.registry
            inst = registry.queryAdapter(request, ISkinObject, name=self.name)
            if inst is None:
                inst = registry.getUtility(ISkinObject, name=self.name)
            return inst(context=context, request=request, **kw)

        result = self.render(context=context, request=request, **kw)
        if isinstance(result, string_types):
            response = Response(body=result)
        else:
            response = Response(app_iter=result)
            response.content_length = os.path.getsize(self.path)

        content_type = self.content_type
        if content_type is None:
            content_type = type(self).content_type
        response.content_type = content_type
        response.charset = self.encoding
        return response
コード例 #36
0
ファイル: attendee_service.py プロジェクト: Mac-lp3/ufree
    def update_attendee (self, req):
        '''
        Updates an attendee's details such as name or email address
        '''
        try:
            if 'id' not in req.json_body:
                raise ServiceException('Id was not found on this request')
            self.__attendeeValidator.validate_attendee_request(req)
            data = self.__attendee_dao.update_attendee(req.json_body)
            response = Response(content_type='application/json', status=200)
            response.charset = 'UTF-8'
            response.json_body = json.dumps(data)
        except BaseAppException as e:
            # Handle DAO/Validation errors
            raise ServiceException(str(e))
        except Exception as e:
            # Handle unexpected errors
            print(e, sys.exc_info())
            raise ServiceException(
                'An error occurred while updating your info.'
            )

        return response
コード例 #37
0
def convertToCSVLegacy(context, request):

    students = json.loads(request.POST['json_data'])

    data = {
            'Student Last Name': [],
            'Student First Name': [],
            'SSID (consistent with TIDE)': [],
            'Grade': [],
            'Educator(s) completing ISAAP': [],
            'Teacher of Record': [],
            'School ID': [],
            'School Name': [],
            'Abacus': [],
            '*Alternate Response Options (including any external devices/assistive technologies)': [],
            'American Sign Language for ELA Listening and Math Items': [],
            'Bilingual Dictionary for ELA Full Writes (ET)': [],
            'Braille': [],
            'Calculator': [],
            'Closed Captioning for ELA Listening Items': [],
            'Color Contrast (EMBEDDED)': [],
            '*Color Contrast (NON-EMBEDDED)': [],
            'Color Overlays': [],
            '*Magnification': [],
            'Masking': [],
            'Multiplication Table': [],
            'Noise Buffers': [],
            '*Print on Demand': [],
            '*Read Aloud for ELA Reading Passages Grades 6-8 and 11': [],
            '*Read Aloud for Math and ELA Items': [],
            '*Scribe': [],
            '*Scribe (for ELA non-writing items and Math items)': [],
            'Separate Setting': [],
            '*Speech-to-text': [],
            '*Stacked Translations for Math': [],
            '*Text-to-speech for ELA Reading Passages Grades 6-8 and 11': [],
            '*Text-to-speech for Math and ELA Items': [],
            'Translated Text Directions': [],
            'Translated Test Directions for Math': [],
            '*Translation Glossaries for Math (ET) (EMBEDDED)': [],
            'Translation Glossaries for Math (ET) (NON-EMBEDDED)': [],
        }

    for el in students:
        data['Student Last Name'].append(el['lastname'])
        data['Student First Name'].append(el['firstname'])
        data['SSID (consistent with TIDE)'].append(el['ssid'])
        data['Grade'].append(el['grade']['selected']['value'])
        data['Educator(s) completing ISAAP'].append('')
        data['Teacher of Record'].append(el['teacher'])
        data['School ID'].append(el['school_id'])
        data['School Name'].append(el['school_name'])

        try:
            data['Abacus'].append(el['accommodations']['11']['selected']['value'])
        except (NameError, TypeError):
            data['Abacus'].append('')

        try:
            data['*Alternate Response Options (including any external devices/assistive technologies)'].append(el['accommodations']['9']['selected']['value'])
        except (NameError, TypeError):
            data['*Alternate Response Options (including any external devices/assistive technologies)'].append('')

        try:
            data['American Sign Language for ELA Listening and Math Items'].append(el['accommodations']['12']['selected']['value'])
        except (NameError, TypeError):
            data['American Sign Language for ELA Listening and Math Items'].append('')


        try:
            data['Bilingual Dictionary for ELA Full Writes (ET)'].append(el['accommodations']['13']['selected']['value'])
        except (NameError, TypeError):
            data['Bilingual Dictionary for ELA Full Writes (ET)'].append('')


        try:
            data['Braille'].append(el['accommodations']['10']['selected']['value'])
        except (NameError, TypeError):
            data['Braille'].append('')


        try:
            data['Calculator'].append(el['accommodations']['5']['selected']['value'])
        except (NameError, TypeError):
            data['Calculator'].append('')


        try:
            data['Closed Captioning for ELA Listening Items'].append(el['accommodations']['13']['selected']['value'])
        except (NameError, TypeError):
            data['Closed Captioning for ELA Listening Items'].append('')


        try:
            data['Color Contrast (EMBEDDED)'].append(el['designated']['1']['selected']['value'])
        except (NameError, TypeError):
            data['Color Contrast (EMBEDDED)'].append('')


        try:
            data['*Color Contrast (NON-EMBEDDED)'].append(el['designated']['5']['selected']['value'])
        except (NameError, TypeError):
            data['*Color Contrast (NON-EMBEDDED)'].append('')

        try:
            data['Color Overlays'].append(el['designated']['6']['selected']['value'])
        except (NameError, TypeError):
            data['Color Overlays'].append('')

        try:
            data['*Magnification'].append(el['designated']['7']['selected']['value'])
        except (NameError, TypeError):
             data['*Magnification'].append('')

        try:
            data['Masking'].append(el['designated']['2']['selected']['value'])
        except (NameError, TypeError):
            data['Masking'].append('')

        try:
            data['Multiplication Table'].append(el['accommodations']['6']['selected']['value'])
        except (NameError, TypeError):
            data['Multiplication Table'].append('')

        try:
            data['Noise Buffers'].append(el['accommodations']['2']['selected']['value'])
        except (NameError, TypeError):
            data['Noise Buffers'].append('')

        try:
            data['*Print on Demand'].append(el['accommodations']['1']['selected']['value'])
        except (NameError, TypeError):
            data['*Print on Demand'].append('')

        try:
            data['*Read Aloud for ELA Reading Passages Grades 6-8 and 11'].append(el['accommodations']['4']['selected']['value'])
        except (NameError, TypeError):
            data['*Read Aloud for ELA Reading Passages Grades 6-8 and 11'].append('')

        try:
            data['*Read Aloud for Math and ELA Items'].append(el['designated']['9']['selected']['value'])
        except (NameError, TypeError):
            data['*Read Aloud for Math and ELA Items'].append('')

        try:
            data['*Scribe'].append(el['accommodations']['8']['selected']['value'])
        except (NameError, TypeError):
            data['*Scribe'].append('')

        try:
            data['*Scribe (for ELA non-writing items and Math items)'].append(el['designated']['15']['selected']['value'])
        except (NameError, TypeError):
            data['*Scribe (for ELA non-writing items and Math items)'].append('')

        try:
            data['Separate Setting'].append(el['designated']['8']['selected']['value'])
        except (NameError, TypeError):
            data['Separate Setting'].append('')

        try:
            data['*Speech-to-text'].append(el['accommodations']['7']['selected']['value'])
        except (NameError, TypeError):
            data['*Speech-to-text'].append('')

        try:
            data['*Stacked Translations for Math'].append(el['designated']['12']['selected']['value'])
        except (NameError, TypeError):
            data['*Stacked Translations for Math'].append('')

        try:
            data['*Text-to-speech for ELA Reading Passages Grades 6-8 and 11'].append(el['accommodations']['3']['selected']['value'])
        except (NameError, TypeError):
            data['*Text-to-speech for ELA Reading Passages Grades 6-8 and 11'].append('')

        try:
            data['*Text-to-speech for Math and ELA Items'].append(el['designated']['3']['selected']['value'])
        except (NameError, TypeError):
            data['*Text-to-speech for Math and ELA Items'].append('')

        try:
            data['Translated Text Directions'].append(el['designated']['16']['selected']['value'])
        except (NameError, TypeError):
            data['Translated Text Directions'].append('')

        try:
            data['Translated Test Directions for Math'].append(el['designated']['10']['selected']['value'])
        except (NameError, TypeError):
            data['Translated Test Directions for Math'].append('')

        try:
            data['*Translation Glossaries for Math (ET) (EMBEDDED)'].append(el['designated']['11']['selected']['value'])
        except (NameError, TypeError):
            data['*Translation Glossaries for Math (ET) (EMBEDDED)'].append('')

        try:
            data['Translation Glossaries for Math (ET) (NON-EMBEDDED)'].append(el['designated']['14']['selected']['value'])
        except (NameError, TypeError):
            data['Translation Glossaries for Math (ET) (NON-EMBEDDED)'].append('')


    col_order = [
            'Student Last Name',
            'Student First Name',
            'SSID (consistent with TIDE)',
            'Grade',
            'Educator(s) completing ISAAP',
            'Teacher of Record',
            'School ID',
            'School Name',
            'Abacus',
            '*Alternate Response Options (including any external devices/assistive technologies)',
            'American Sign Language for ELA Listening and Math Items',
            'Bilingual Dictionary for ELA Full Writes (ET)',
            'Braille',
            'Calculator',
            'Closed Captioning for ELA Listening Items',
            'Color Contrast (EMBEDDED)',
            '*Color Contrast (NON-EMBEDDED)',
            'Color Overlays',
            '*Magnification',
            'Masking',
            'Multiplication Table',
            'Noise Buffers',
            '*Print on Demand',
            '*Read Aloud for ELA Reading Passages Grades 6-8 and 11',
            '*Read Aloud for Math and ELA Items',
            '*Scribe',
            '*Scribe (for ELA non-writing items and Math items)',
            'Separate Setting',
            '*Speech-to-text',
            '*Stacked Translations for Math',
            '*Text-to-speech for ELA Reading Passages Grades 6-8 and 11',
            '*Text-to-speech for Math and ELA Items',
            'Translated Text Directions',
            'Translated Test Directions for Math',
            '*Translation Glossaries for Math (ET) (EMBEDDED)',
            'Translation Glossaries for Math (ET) (NON-EMBEDDED)',
        ]


    df = pd.DataFrame(data)
    df = df[col_order]

    
    response = Response(content_type='application/octet-stream')
    response.headers['Content-Disposition'] = 'attachment; filename="data.csv"'
    response.charset = 'utf8'
    response.body = df.to_csv(index=False).encode(encoding='UTF-8',errors='strict')
    return response
コード例 #38
0
def convertToCSV(context, request):

    students = json.loads(request.POST['json_data'])

    data = {
            'StudentIdentifier': [],
            'StateAbbreviation': [],
            'Subject': [],
            'AmericanSignLanguage': [],
            'ColorContrast': [],
            'ClosedCaptioning': [],
            'Language': [],
            'Masking': [],
            'PermissiveMode': [],
            'PrintOnDemand': [],
            'Zoom': [],
            'StreamlinedInterface': [],
            'TexttoSpeech': [],
            'Translation': [],
            'NonEmbeddedDesignatedSupports': [],
            'NonEmbeddedAccommodations': [],
            'Other': [],
        }

    for el in students:

        data['StudentIdentifier'].append(el['ssid'])
        data['StateAbbreviation'].append(el['state'])
        data['Subject'].append(el['subject']['selected']['value'])

        
        try:
            data['AmericanSignLanguage'].append(el['accommodations']['12']['selected']['value'])
        except (NameError, TypeError):
            data['AmericanSignLanguage'].append('')

        try:
            data['ColorContrast'].append(el['designated']['1']['selected']['value'])
        except (NameError, TypeError):
            data['ColorContrast'].append('')

        try:
            data['ClosedCaptioning'].append(el['accommodations']['13']['selected']['value'])
        except (NameError, TypeError):
            data['ClosedCaptioning'].append('')

        try:
            data['Language'].append(el['language']['selected']['value'])
        except (NameError, TypeError):
            data['Language'].append('')


        try:
            data['Masking'].append(el['designated']['2']['selected']['value'])
        except (NameError, TypeError):
            data['Masking'].append('')

        try:
            data['PermissiveMode'].append(el['permissive_mode']['selected']['value'])
        except (NameError, TypeError):
            data['PermissiveMode'].append('')

        try:
            data['PrintOnDemand'].append(el['accommodations']['1']['selected']['value'])
        except (NameError, TypeError):
            data['PrintOnDemand'].append('')

        try:
            data['Zoom'].append(el['designated']['18']['selected']['value'])
        except (NameError, TypeError):
            data['Zoom'].append('')

        try:
            data['StreamlinedInterface'].append(el['designated']['17']['selected']['value'])
        except (NameError, TypeError):
            data['StreamlinedInterface'].append('')

        try:
            data['TexttoSpeech'].append(el['designated']['3']['selected']['value'])
        except (NameError, TypeError):
            data['TexttoSpeech'].append('')

        try:
            data['Translation'].append(el['designated']['11']['selected']['value'])
        except (NameError, TypeError):
            data['Translation'].append('')

        non_des = ''
        # Bilingual Dictionary
        try:
            bil = el['designated']['13']['selected']['value']
            if bil == None:
                raise TypeError
            non_des += bil + ";"
        except (NameError, TypeError):
            pass
        # Color Contrast
        try:
            color_contrast = el['designated']['5']['selected']['value']
            if color_contrast == None:
                raise TypeError
            non_des += color_contrast + ";"
        except (NameError, TypeError):
            pass
        # Color Overlay
        try:
            color_overlay = el['designated']['6']['selected']['value']
            if color_overlay == None:
                raise TypeError
            non_des += color_overlay + ";"
        except (NameError, TypeError):
            pass
        # Magnification
        try:
            mag = el['designated']['7']['selected']['value']
            if mag == None:
                raise TypeError
            non_des += mag + ";"
        except (NameError, TypeError):
            pass
        # Noise Buffers
        try:
            noise_buff = el['accommodations']['2']['selected']['value']
            if noise_buff == None:
                raise TypeError
            if noise_buff == 'NEA_NoiseBuf':
                noise_buff = 'NEDS_NoiseBuf'
            non_des += noise_buff + ";"
        except (NameError, TypeError):
            pass
        # Read Aloud
        try:
            read_aloud = el['designated']['9']['selected']['value']
            if read_aloud == None:
                raise TypeError
            non_des += read_aloud + ";"
        except (NameError, TypeError):
            pass
        # Read Aloud in Spanish
        try:
            non_des += ''
        except (NameError, TypeError):
            pass
        # Separate Setting
        try:
            seperate_setting = el['designated']['8']['selected']['value']
            if seperate_setting == None:
                raise TypeError
            non_des += seperate_setting + ";"
        except (NameError, TypeError):
            pass
        # Translated Test Directions
        try:
            translated = el['designated']['16']['selected']['value']
            if translated == None:
                raise TypeError
            non_des += translated + ";"
        except (NameError, TypeError):
            pass
        # Translation (Glossary) 
        try:
            translation = el['designated']['14']['selected']['value']
            if translation == None:
                raise TypeError
            if translation == 'English':
                translation = 'TDS_WL_Glossary'
            non_des += translation + ";"
        except (NameError, TypeError):
            pass

        non_des = non_des.replace(';;', ';')
        data['NonEmbeddedDesignatedSupports'].append(non_des)


        non_accom = ''
        # Abacus
        try:
            abacus = el['accommodations']['11']['selected']['value']
            if abacus == None:
                raise TypeError
            if abacus == 'NEA_Abacus (Math only)':
                abacus = 'NEA_Abacus'
            non_accom += abacus + ";"
        except (NameError, TypeError):
            pass
        # *Alternate Response Options (including any external devices/assistive technologies)
        try:
            alt = el['accommodations']['9']['selected']['value']
            if alt == None:
                raise TypeError
            non_accom += alt + ";"
        except (NameError, TypeError):
            pass
        # Calculator
        try:
            calc = el['accommodations']['5']['selected']['value']
            if calc == None:
                raise TypeError
            if calc == 'NEA_Calc (Math only)':
                calc = 'NEA_Calc'
            non_accom += calc + ";"
        except (NameError, TypeError):
            pass
        # Multiplication Table
        try:
            mult = el['accommodations']['6']['selected']['value']
            if mult == None:
                raise TypeError
            if multi == 'NEA_MT (Math only)':
                multi = 'NEA_MT'
            non_accom += multi + ";"
        except (NameError, TypeError):
            pass
        # Print on Demand
        #try:
        #    non_accom += el['accommodations']['1']['selected']['value'] + ";"
        #except (NameError, TypeError):
        #    pass
        # Read Aloud - *Read Aloud for ELA Reading Passages Grades 6-8 and 11
        try:
            read = el['accommodations']['4']['selected']['value']
            if read == None:
                raise TypeError
            if read == 'NEA_RA_Stimuli (ELA only)':
                read = 'NEA_RA_Stimuli'
            non_accom += read + ";"
        except (NameError, TypeError):
            pass
        # Scribe
        try:
            scribe = el['accommodations']['8']['selected']['value']
            if scibe == None:
                raise TypeError
            if scribe == 'NEA_SC_WritItems (ELA only)':
                scribe = 'NEA_SC_WritItems'
            non_accom += scribe + ";"
        except (NameError, TypeError):
            pass
        # Speech-to-text
        try:
            speech = el['accommodations']['7']['selected']['value']
            if speech == None:
                raise TypeError
            non_accom += speech + ";"
        except (NameError, TypeError):
            pass

        non_accom = non_accom.replace(';;', ';')
        data['NonEmbeddedAccommodations'].append(non_accom)


        try:
            data['Other'].append('')
        except (NameError, TypeError):
            data['Other'].append('')



    col_order = [
            'StudentIdentifier',
            'StateAbbreviation',
            'Subject',
            'AmericanSignLanguage',
            'ColorContrast',
            'ClosedCaptioning',
            'Language',
            'Masking',
            'PermissiveMode',
            'PrintOnDemand',
            'Zoom',
            'StreamlinedInterface',
            'TexttoSpeech',
            'Translation',
            'NonEmbeddedDesignatedSupports',
            'NonEmbeddedAccommodations',
            'Other',
        ]


    df = pd.DataFrame(data)
    df = df[col_order]

    
    response = Response(content_type='application/octet-stream')
    response.headers['Content-Disposition'] = 'attachment; filename="data.csv"'
    response.charset = 'utf8'
    response.body = df.to_csv(index=False).encode(encoding='UTF-8',errors='strict')
    return response
コード例 #39
0
def convertToCSV2(context, request):

    session = request.db

    students = json.loads(request.POST['json_data'])

    #students = request.json_body['students']

    fp = ''

    for el in students:
        fp += el['firstname']+','+el['lastname']+','+el['ssid']+','+el['school']+','+el['grade']+','+el['teacher']

        this_item = el['universal_tools']
        this_list = (
                'Breaks', 
                'Calculator', 
                'Digital Notes' , 
                'English Dictionary', 
                'English Glossary', 
                'Expandable Passages', 
                'Global Notes', 
                'Highlighter', 
                'Keyboard Navigation', 
                'Mark for Review', 
                'Math Tools', 
                'Spell Check', 
                'Strikethrough', 
                'Writing Tools', 
                'Zoom'
                )
        for el2 in this_list:
            x = list(filter(lambda x: x['text'] == el2, this_item))[0]
            if (x['select'] == True):
                fp += ','+x['text']
            else:
                fp += ',,'



        this_item = el['universal_tools_ne']
        this_list = (
                'Breaks', 
                'Scratch Paper', 
                'Thesaurus' , 
                'English Dictionary', 
                )
        for el2 in this_list:
            x = list(filter(lambda x: x['text'] == el2, this_item))[0]
            if (x['select'] == True):
                fp += ','+x['text']
            else:
                fp += ',,'


        this_item = el['ident_student_needs']
        this_list = (
                'Individualized Education Program', 
                '504 Plan', 
                'Educator(s) Recommendation', 
                )
        for el2 in this_list:
            x = list(filter(lambda x: x['text'] == el2, this_item))[0]
            if (x['select'] == True):
                fp += ','+x['text']
            else:
                fp += ',,'


        fp += '\n'

    response = Response(content_type='application/octet-stream')
    response.headers['Content-Disposition'] = 'attachment; filename="data.csv"'
    response.charset = 'utf8'
    response.body = fp.encode(encoding='UTF-8',errors='strict')
    return response
コード例 #40
0
def login_user(request):

    try:
        email = request.json_body.get('email')
        firebase_token = request.json_body.get('firebaseToken')
        is_anonymous = request.json_body.get('isAnonymous')
        firebase_user_id = request.json_body.get('firebaseUserId')
        google_token = request.json_body.get('googleToken')
        branch_data = request.json_body.get('branchData')
        prev_firebase_user_id = request.json_body.get('prevFirebaseUserId')
    except ValueError:
        raise ValidationError('ERR_INVALID_AUTH_PARAM')

    if get_is_production() or email != 'oice-dev':
        try:
            auth.verify_id_token(firebase_token)
        except ValueError:
            raise ValidationError('ERR_FIREBASE_AUTH_ERROR')
        except AppIdentityError:
            raise ValidationError('ERR_INVALID_FIREBASE_TOKEN')

    old_auth_id = authenticated_userid(request)

    fetch_username = email
    if is_anonymous and firebase_user_id:
        fetch_username = firebase_user_id

    # Init these bool here to avoid scope issue
    is_first_login = False
    is_trial_ended = False

    log_dict = {
        'topic': 'actionUser',
        'isAnonymous': 'true' if is_anonymous else 'false',
        'isDeeplink': 'false',
    }
    if branch_data:
        log_dict.update({
            'channel':
            dict_get_value(branch_data, ['~channel'], 'direct'),
            'isDeeplink':
            'true',
        })
        log_dict = set_basic_info_referrer_log(
            dict_get_value(branch_data, ['+referrer'], 'none'),
            dict_get_value(branch_data, ['referrer2'], 'none'), log_dict)
        oice_source = OiceQuery(DBSession).get_by_uuid(
            dict_get_value(branch_data, ['uuid']))
        if oice_source:
            log_dict = set_basic_info_oice_source_log(
                oice_source.story.users[0], oice_source, log_dict)

    try:
        user = UserQuery(DBSession).fetch_user_by_email(
            email=fetch_username).one()
    except NoResultFound:

        user = User(email=fetch_username, is_anonymous=is_anonymous)
        if firebase_user_id:
            user.display_name = firebase_user_id
        DBSession.add(user)
        DBSession.flush()

        is_first_login = True
        is_trial_ended = False

        # log
        log_dict.update({'action': 'createUser'})
        log_dict = set_basic_info_user_log(user, log_dict)
        log_dict = set_basic_info_log(request, log_dict)
        log_message(KAFKA_TOPIC_USER, log_dict)

    else:
        user.last_login_at = datetime.datetime.utcnow()

        if not user.is_anonymous:
            sample_story = StoryQuery(DBSession).get_sample_story(
                user.language)
            story = next((user_story for user_story in user.stories
                          if sample_story.id == user_story.fork_of), None)
            if not story:
                story = fork_story(DBSession, sample_story)
                sample_oice = OiceQuery(DBSession).get_sample_oice(
                    language=user.language)
                oice = fork_oice(DBSession, story, sample_oice)
                user.stories.append(story)

        if user.is_trial:
            if user.is_paid(
            ) and user.expire_date < datetime.datetime.utcnow():
                user.role = 'user'
                update_user_mailchimp_stage(user=user, stage=5)
            if user.is_free():
                user.is_trial = False
                is_trial_ended = True
        else:
            # if user.is_free() and not user.expire_date:
            # Disabled trial due to busines request
            # UserOperations.start_trial(user)
            is_trial_ended = False

        is_first_login = False

        if not old_auth_id or request.headers.get('x-oice-app-version'):
            # log
            is_redeem_account = prev_firebase_user_id and firebase_user_id != prev_firebase_user_id

            log_dict.update({
                'action':
                'redeemAccount' if is_redeem_account else 'login',
            })
            log_dict = set_basic_info_user_log(user, log_dict)
            log_dict = set_basic_info_log(request, log_dict)
            log_message(KAFKA_TOPIC_USER, log_dict)

            if is_redeem_account:
                handle_anonymous_user_app_story_progress(is_existing_user=True, \
                                                         prev_user_email=prev_firebase_user_id, \
                                                         new_user=user)

    photo_url = request.json_body.get('photoURL', None)
    if photo_url and user.avatar_storage is None:
        r = requests.get(photo_url)
        avatar = BytesIO(r.content)
        factory = pyramid_safile.get_factory()
        handle = factory.create_handle('avatar.png', avatar)
        user.import_handle(handle)

    language = request.json_body.get('language', None)
    normalized_language = None

    if language and user.language is None:
        normalized_language = normalize_language(language)
    if normalized_language:
        user.language = normalized_language
        # derive ui_language when creating user
        user.ui_language = normalize_ui_language(normalized_language)

    if (is_first_login or user.is_anonymous) and google_token:

        display_name = request.json_body.get('displayName', None)

        if email:
            user.email = email
            if not display_name:
                display_name = email.split('@')[0]

        if display_name:
            user.display_name = display_name

        sample_story = StoryQuery(DBSession).get_sample_story(
            normalized_language)
        story = fork_story(DBSession, sample_story)
        sample_oice = OiceQuery(DBSession).get_sample_oice(
            language=normalized_language)
        oice = fork_oice(DBSession, story, sample_oice)

        # open a public library for new user
        library = create_user_public_library(DBSession, user.display_name)

        user.stories.append(story)
        user.libraries.append(library)
        user.libraries_selected.append(library)

        # pre-select default libraries for new user
        default_libs = LibraryQuery(DBSession).fetch_default_libs()
        user.libraries_purchased.extend(default_libs)
        user.libraries_selected.extend(default_libs)

        # Disabled trial due to busines request
        # UserOperations.start_trial(user)

        user.last_login_at = datetime.datetime.utcnow()
        subscribe_mailchimp(google_token, user, language=language)

        # update elastic search when create user
        update_elastic_search_user(user.display_name, email)

        if is_first_login and request.headers.get('x-oice-app-version'):
            # log
            log_dict.update({'action': 'bindAccount'})
            log_dict = set_basic_info_user_log(user, log_dict)
            log_dict = set_basic_info_log(request, log_dict)
            log_message(KAFKA_TOPIC_USER, log_dict)

            handle_anonymous_user_app_story_progress(is_existing_user=False, \
                                                     prev_user_email=prev_firebase_user_id, \
                                                     new_user=user)

        user.is_anonymous = False

    serialize_user = user.serialize()
    serialize_user['isFirstLogin'] = is_first_login
    serialize_user['isTrialEnded'] = is_trial_ended

    serialize_user['intercomUserHash'] = hmac.new(
        bytes(get_intercom_secret_key().encode('utf-8')),
        bytes(str(user.id).encode('utf-8')),
        digestmod=hashlib.sha256).hexdigest()

    response = Response()
    response.status_code = 200
    response.headers = remember(request, user.email)
    response.content_type = 'application/json'
    response.charset = 'UTF-8'
    response.text = json.dumps({'code': 200, 'user': serialize_user})

    return response