当前位置: 首页>>代码示例>>Python>>正文


Python Response.write方法代码示例

本文整理汇总了Python中pyramid.response.Response.write方法的典型用法代码示例。如果您正苦于以下问题:Python Response.write方法的具体用法?Python Response.write怎么用?Python Response.write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pyramid.response.Response的用法示例。


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

示例1: login

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import write [as 别名]
    def login(self):
        """ Call the authomatic functions for login with google through
        oauth2. Store the results for primitive session management and
        authorization.
        """
        user_id = self.request.environ.get("REMOTE_USER")
        log.info("Inside view login user: [%s]", user_id)

        if user_id is not None:
            log.info("Environment authentication")
            return self.successful_response(user_id, user_id)


        # If no environmental bypass authentication is provided, use
        # authomatic
        response = Response()
        result = authomatic.login(WebObAdapter(self.request, response),
                                  "google")

        # Is the only way to get around this hole in coverage to walk
        # through an authomatic login procedure with testapp submitting
        # username and password credentials?
        if result != None:
            if result.user:
                result.user.update()
                return self.successful_response(result.user.email,
                                                result.user.name)

        log.critical("Error authomatic: %s", result)
        response.write("<h2>found error in authomatic</h2>")
        return response
开发者ID:WasatchPhotonics,项目名称:CookBook,代码行数:33,代码来源:views.py

示例2: settings_save

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import write [as 别名]
def settings_save(_context, request):
    data = request.POST.get('data')
    response = Response()
    if data is not None:
        data = json.loads(data)
        for key in data:
            k = key.replace("___", ".")
            setting_data = request.db.settings.find_one({"key": k })
            if setting_data is None:
                setting = create_setting(k)
            else:
                setting = Setting().deserialize(setting_data)
            
            if isinstance(data[key], str) or isinstance(data[key], unicode):
                Setting().set_value(setting, 'value', data[key])
            else:
                Setting().set_value(setting, 'value', json.dumps(data[key]))
            
            # Save in mongoDB
            obj = Setting().serialize(setting)
            if obj['_id'] == colander.null:
                del obj['_id']
            else:
                obj['_id'] = ObjectId(obj['_id'])
            #logger.debug('save= %s'%(obj))
            request.db.settings.save(obj)
                                    
    messages.created_msg(request, _('Settings modified successfully'), 'success')
    response.write('SUCCESS')
    return response
开发者ID:gecos-team,项目名称:gecoscc-ui,代码行数:32,代码来源:settings.py

示例3: login

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import write [as 别名]
def login(request):
    provider_name = request.matchdict.get('provider_name')
    response = Response()
    result = authomatic.login(WebObAdapter(request, response), provider_name)

    if result:
        response.write(fixtures.render_login_result('pyramid', result).encode())

    return response
开发者ID:88blk88,项目名称:authomatic,代码行数:11,代码来源:main.py

示例4: pdf

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import write [as 别名]
 def pdf(self):
     id = self.request.matchdict['id']
     file = self._generate_pdf(id)
     
     if not file:
         raise HTTPForbidden()
     else:
         response = Response(content_type='application/pdf')
         response.write(file)
         return response
开发者ID:polklibrary,项目名称:quizsmith,代码行数:12,代码来源:score.py

示例5: respond_bed_csv

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import write [as 别名]
def respond_bed_csv(table, fmt, hinfo, dicts):
    response = Response(content_type="text/plain")
    tup = (table, fmt)
    header_tmp = EXPORT_HEADERS[tup]
    header = header_tmp % hinfo + "\n"
    response.write(header)
    fmt = EXPORT_FORMATS[tup]
    for d in dicts:
        line = fmt % d + "\n"
        response.write(line)
    return response
开发者ID:tdhock,项目名称:SegAnnDB,代码行数:13,代码来源:views.py

示例6: login

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import write [as 别名]
def login(request):
    # Useful:
    # https://peterhudec.github.io/authomatic/examples/pyramid-simple.html
    response = Response()
    provider_name = request.matchdict.get('provider_name')
    result = authomatic.login(WebObAdapter(request, response), provider_name)
    
    # Do not write anything to the response if there is no result!
    if result:
        # If there is result, the login procedure is over and we can write to response.
        response.write('<a href="..">Home</a>')
        # from pprint import pprint
        # pprint (vars(your_object))
        
        if result.error:
            response.write(u'<h2>ERROR in login: {0}</h2>'.format(result.error.message))
        
        elif result.user:
            # OAuth 2.0 and OAuth 1.0a provide only limited user data on login,
            # We need to update the user to get more info.
            if not (result.user.name and result.user.id):
                result.user.update()

            row = DBSession.query(User).filter_by(google_id=result.user.id).first()
            if not row:
                user_id = DBSession.query(User).count()
                row = User(id=user_id, google_id=result.user.id, name="TMP", email=result.user.email)
                DBSession.add(row)
                transaction.commit()
            else:
                user_id = row.id

            headers = remember(request, user_id)
            log.debug("user id: {}".format(user_id))
            response.headerlist.extend(headers)
            # response.write(u'<h1>Hi {0}</h1>'.format(result.user.name))
            # response.write(u'<h2>Your id is: {0}</h2>'.format(result.user.id))
            # response.write(u'<h2>Your email is: {0}</h2>'.format(result.user.email))

            url = request.route_url('home')
            return HTTPFound(location=url, headers=headers)

    return response
开发者ID:malnoxon,项目名称:rsstory,代码行数:45,代码来源:views.py

示例7: apps_csv_view

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import write [as 别名]
def apps_csv_view(request):

    sort_input = '+application'
    app_act = AppsAction(sort=sort_input, limit=1000)
    applications = app_act.get_applications()

    response = Response()
    response.content_type = "text/plain"
    # If download needs to be triggered add "attachment; " before filename=...
    response.headers.add("Content-Disposition", "attachment; filename=applications.txt")

    response.write(codecs.BOM_UTF8)
    writer = csv.writer(response, delimiter=';', escapechar='"', quoting=csv.QUOTE_ALL)
    writer.writerow(['Nr', 'Name', 'Alias', 'Brand', 'Lifecycle', 'Lang', 'Note', 'Tag name',
                     'Tag value', 'EA GUID'])
    for i, app in enumerate(applications):
        for tag in app.properties:
            writer.writerow([i+1, app.name, app.alias, app.stereotype, app.status, app.gentype,
                             (app.note or '').replace('\r\n', ' '), tag.property, tag.value, app.ea_guid])

    return response
开发者ID:margus-parnsalu,项目名称:Lifecycle,代码行数:23,代码来源:views_apps.py

示例8: settings_save

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import write [as 别名]
def settings_save(context, request):
    data = request.POST.get('data')
    settings = request.db.settings.find()
    response = Response()
    if data is not None:
        data = json.loads(data)
        for key in data:
            k = key.replace("___", ".")
            setting_data = request.db.settings.find_one({"key": k })
            if setting_data is None:
                setting = create_setting(k)
            else:
                setting = Setting().deserialize(setting_data)
            
            if isinstance(data[key], str) or isinstance(data[key], unicode):
                Setting().set_value(setting, 'value', data[key])
            else:
                Setting().set_value(setting, 'value', json.dumps(data[key]))
            
            # Save in mongoDB
            obj = Setting().serialize(setting)
            if obj['_id'] == colander.null:
                del obj['_id']
            else:
                obj['_id'] = ObjectId(obj['_id'])
            #logger.debug('save= %s'%(obj))
            request.db.settings.save(obj)
            
            # If saving "software_profiles", save them also in "software_profiles" collection
            if key == "software_profiles":
                collection = request.db.software_profiles
                # Update the software profiles
                for new_profile in data[key]:
                    name = new_profile['name']
                    db_profile = collection.find_one({'name': name})
                    
                    if not db_profile:
                        collection.insert(new_profile)
                        logger.debug("Created profile: %s" % name)

                    elif new_profile['packages'] != db_profile['packages']:
                        collection.update({'name': name}, new_profile)
                        logger.debug("Updated profile: %s" % name)

                # Check if the user is trying to delete a software profile
                sp_policy = request.db.policies.find_one({"slug" : "package_profile_res"})
                if not sp_policy:
                    messages.created_msg(request, _('Software Profiles policy not found'), 'warning')
                    response.write('SUCCESS')
                    return response
                    
                db_profiles = collection.find()
                for profile in db_profiles:
                    profile_found = False
                    for new_profile in data[key]:
                        if new_profile['name'] == profile['name']:
                            profile_found = True
                            
                    if not profile_found:
                        # Check if we can delete the software profile
                        # (the software profile is not in use)
                        logger.debug("Try to delete: %s - %s"%(str(profile['_id']), profile['name']))
                        obj_related_list = "policies.%s.object_related_list"%(str(sp_policy['_id']))
                        profile_id = str(profile['_id'])
                        nnodes = request.db.nodes.find({obj_related_list : profile_id}).count()
                        logger.debug("Found %s nodes"%(nnodes))
                        
                        if nnodes == 0:
                            # It it's not used we can delete it
                            collection.remove({"_id": profile['_id']})
                        else:
                            # It's used, so we can't delete it
                            messages.created_msg(request, _('Software Profile in use: %s')%(profile['name']), 'warning')
                            response.write('SUCCESS')
                            return response
                        
                        
                        
    messages.created_msg(request, _('Settings modified successfully'), 'success')
    response.write('SUCCESS')
    return response
开发者ID:joroca,项目名称:gecoscc-ui,代码行数:83,代码来源:settings.py

示例9: login

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import write [as 别名]
def login(request):
    response = Response()
    # get provider
    provider = request.matchdict.get('provider')

    result = authomatic.login(WebObAdapter(request, response),provider)

    # Do not write anything to the response if there is no result!
    if result:
        # If there is result, the login procedure is over and we can write to response.
        #response.write('<a href="..">Home</a>')
        
        if result.error:
            log.error(result.error.message)
            # Login procedure finished with an error.
            response.write('<h2>Damn that error: {}</h2>'.format(result.error.message))
            #print result.error.message
        
        elif result.user:
            # Hooray, we have the user!
            
            # OAuth 2.0 and OAuth 1.0a provide only limited user data on login,
            # We need to update the user to get more info.
            if not (result.user.name and result.user.id):
                result.user.update()

            # check is user already exists, if not, then add
            thisuser = None
            try:
                thisuser = DBSession.query(User).filter(User.providerid == result.user.id)\
                    .filter(User.provider == provider).first()
                if not thisuser:
                    NewUser = User(result.user.id, provider, result.user.credentials.serialize())
                    
                    DBSession.add(NewUser)
                    DBSession.flush()
                    # default profile name is whatever the provider display name is
                    NewProfile = UserProfile(NewUser.id)
                    NewProfile.displayname = result.user.name
                    NewProfile.last_login = datetime.datetime.utcnow()
                    DBSession.add(NewProfile)
                    DBSession.flush()

                    thisuser = DBSession.query(User).filter(User.providerid == result.user.id)\
                        .filter(User.provider == provider).first()

                    # redirect to fill out userprofile?  
                else:
                    thisuser.last_login = datetime.datetime.utcnow()
                    DBSession.add(thisuser)
                    DBSession.flush()          
            except DBAPIError as e:
                log.error(e.message)


            login_url = request.route_url('login', provider=provider)
            referrer = request.url
            if referrer == login_url:
                referrer = request.route_url('home') # never use the login form itself as came_from
            came_from = request.params.get('came_from', referrer)
            headers = remember(request, thisuser.id)
            
            return HTTPFound(location = request.route_url('home'), headers = headers)
            
            # Welcome the user.
            response.write('<h1>Hi {}</h1>'.format(result.user.name))
            response.write('<h2>Your id is: {}</h2>'.format(result.user.id))
            response.write('<h2>Your email is: {}</h2>'.format(result.user.email))
            
            # Seems like we're done, but there's more we can do...


            
            # If there are credentials (only by AuthorizationProvider),
            # we can _access user's protected resources.
            if result.user.credentials:
                
                # Each provider has it's specific API.
                if result.provider.name == 'fb':
                    response.write('Your are logged in with Facebook.<br />')
                    
                    # We will access the user's 5 most recent statuses.
                    url = 'https://graph.facebook.com/{}?fields=feed.limit(5)'
                    url = url.format(result.user.id)
                    
                    # Access user's protected resource.
                    access_response = result.provider.access(url)
                    
                    if access_response.status == 200:
                        # Parse response.
                        statuses = access_response.data.get('feed').get('data')
                        error = access_response.data.get('error')
                        
                        if error:
                            response.write('Damn that error: {}!'.format(error))
                        elif statuses:
                            response.write('Your 5 most recent statuses:<br />')
                            for message in statuses:
                                
                                text = message.get('message')
#.........这里部分代码省略.........
开发者ID:petertirrell,项目名称:LoginProject,代码行数:103,代码来源:views.py

示例10: __call__

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import write [as 别名]
    def __call__(self, request):
        """Processes and dispatches the request"""
        if request.method != 'POST':
            return httpexceptions.HTTPMethodNotAllowed(['POST'])
        
        body = request.body
        stream = None
        timezone_offset = self._get_timezone_offset()

        # Decode the request
        try:
            amf_request = remoting.decode(body, strict=self.strict,
                                          logger=self.logger, 
                                          timezone_offset=timezone_offset)
        except (pyamf.DecodeError, IOError):
            if self.logger:
                self.logger.exception('Error decoding AMF request')

            response = "400 Bad Request\n\nThe request body was unable to " \
                "be successfully decoded."

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % gateway.format_exception()
            return httpexceptions.HTTPBadRequest(detail=response)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            if self.logger:
                self.logger.exception('Unexpected error decoding AMF request')

            response = ("500 Internal Server Error\n\nAn unexpected error "
                "occurred whilst decoding.")

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % gateway.format_exception()
            return httpexceptions.HTTPInternalServerError(detail=response)

        if self.logger:
            self.logger.debug("AMF Request: %r" % amf_request)

        # Process the request
        try:
            response = self.getResponse(request, amf_request)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            if self.logger:
                self.logger.exception('Error processing AMF request')

            response = ("500 Internal Server Error\n\nThe request was "
                "unable to be successfully processed.")

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % gateway.format_exception()
            
            return httpexceptions.HTTPInternalServerError(detail=response)

        if self.logger:
            self.logger.debug("AMF Response: %r" % response)

        # Encode the response
        try:
            stream = remoting.encode(response, strict=self.strict,
                timezone_offset=timezone_offset)
        except:
            if self.logger:
                self.logger.exception('Error encoding AMF request')

            response = ("500 Internal Server Error\n\nThe request was "
                "unable to be encoded.")

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % gateway.format_exception()
            
            return httpexceptions.HTTPInternalServerError(detail=response)

        buf = stream.getvalue()
        
        http_response = Response(content_type=remoting.CONTENT_TYPE)
        http_response.headers['Server'] = gateway.SERVER_NAME
        http_response.write(buf)
        return http_response
开发者ID:kabhinav,项目名称:pyramid_rpc,代码行数:84,代码来源:amfgateway.py

示例11: login

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import write [as 别名]
def login(request):
    session = request.session
    # We will need the response to pass it to the WebObAdapter.
    response = Response()
    # Get the internal provider name URL variable.
    provider_name = request.matchdict.get('provider_name')
    # Start the login procedure.
    result = authomatic.login(WebObAdapter(request, response), provider_name)

    # Do not write anything to the response if there is no result!
    if result:

        if result.error:
            # Login procedure finished with an error.
            response.write(u'<h2>Oops, It seems to have some problem while login. Please try Again: {0}</h2>'.format(result.error.message))

        elif result.user:

            if result.user.credentials:

                # We will access the user's basic info from r_basicprofile.
                url = 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,location,industry,num-connections,summary,picture-url,positions,email-address)?format=json'
                # Access user's protected resource.
                access_response = result.provider.access(url)

                if access_response.status == 200:

                    # Once user logged in store profile id in session.
                    profile_id = access_response.data.get('id')
                    session['session_profile_id'] = profile_id

                    # Open db connection
                    client = pyorient.OrientDB("localhost", 2424)
                    session_id = client.connect("root", "[email protected]")
                    db_name = "LinkRygbee"
                    db_username = "root"
                    db_password = "[email protected]"

                    if client.db_exists(db_name, pyorient.STORAGE_TYPE_MEMORY):
                        client.db_open(db_name, db_username, db_password)
                        print(db_name + " opened successfully")
                    else:
                        print("database [" + db_name + "] does not exist! session ending...")

                    # Check whether user with retrieved profileId exist or not.
                    query = "select count(*) from users where providerId = '{}'"
                    users_result = client.command(query.format(profile_id))
                    user_record = users_result[0]

                    if (user_record.count > 0):
                        # If exist then redirect to profile page.
                        client.db_close()
                        return HTTPFound(location="/profile/" + profile_id)
                    else:
                        # If not then insert new user data into database.
                        emailAddress = access_response.data.get('emailAddress')
                        headline = access_response.data.get('headline')
                        summary = access_response.data.get('summary')
                        firstName = access_response.data.get('firstName')
                        lastName = access_response.data.get('lastName')
                        location = access_response.data.get('location').get('name')
                        industry = access_response.data.get('industry')
                        pictureUrl = access_response.data.get('pictureUrl')

                        # Insert user's details in in Class 'users' in Orientdb.
                        users_details = {'@users': {'providerId': profile_id, 'email': emailAddress, 'firstName': firstName,
                                          'lastName': lastName, 'headline': headline, 'industry': industry,
                                          'pictureUrl': pictureUrl, 'summary': summary, 'location': location}}
                        inserted_user = client.record_create(12, users_details)

                        # Insert user's details in Elasticsearch at users index.
                        es_created_user_detail = es.index('users',
                                                          'user',
                                                          {'providerId': profile_id, 'email': emailAddress,
                                                           'firstName': firstName, 'lastName': lastName,
                                                           'headline': headline, 'industry': industry,
                                                           'pictureUrl': pictureUrl, 'summary': summary,
                                                           'location': location},
                                                          )

                        # Insert user's Experience details in Class 'experience' in Orientdb.
                        positions = access_response.data.get('positions').get('values')
                        for position in positions:
                            month = position.get('startDate').get('month')
                            year = position.get('startDate').get('year')
                            date = str(month) + "/" + str(year)
                            location = position.get('location').get('name')
                            company = position.get('company').get('name')
                            # insert experience
                            users_experience_details = {'@experience': {'title': position.get('title'),
                                                   'summary': position.get('summary'),
                                                   'company': company,
                                                   'date': date,
                                                   'location': location}}
                            inserted_experience = client.record_create(13, users_experience_details)

                            # Create Edge from user to experience. So that we can come to know
                            # Which user has which experience.
                            has_edges = client.command(
                                "create edge has from" + inserted_user._rid + " to " + inserted_experience._rid
#.........这里部分代码省略.........
开发者ID:Rygbee,项目名称:project-LinkRygbee,代码行数:103,代码来源:views.py

示例12: howdy

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import write [as 别名]
def howdy(request):
    response = Response()
    response.write('HELLO THERE')
    return response
开发者ID:malnoxon,项目名称:rsstory,代码行数:6,代码来源:views.py

示例13: delete_profile

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import write [as 别名]
    return view


@view_config(route_name="delete_profile")
def delete_profile(request):
    userid = authenticated_userid(request)
    profile = db.Profile(request.matchdict["name"])
    profile_info = profile.get()
    if profile_info["uploader"] != userid:
        raise Forbidden("profile can only be deleted by uploader")
    try:
        pro_msg = profile.delete()
    except Exception, e:
        pro_msg = "ERROR: " + str(e)
    response = Response(content_type="text/plain")
    response.write(pro_msg)
    return response


@view_config(route_name="secret")
@check_export
def secret(request):
    fn = db.secret_file("%(name)s%(suffix)s" % request.matchdict)
    return FileResponse(fn, request=request)


def table_profiles(names, userid):
    profiles = []
    for pname in names:
        p = db.Profile(pname).get_export(userid)
        # add info for how many annotations for this user.
开发者ID:tdhock,项目名称:SegAnnDB,代码行数:33,代码来源:views.py


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