我的IDE PyCharm在以下代码中抱怨变量response,即使代码正在工作,它也被标记为红色,表示未解析的引用。我想修复它,我想问题是我没有导入响应类。我该怎么做?应该从哪里进口?

class Base2Handler(BaseRequestHandler):
    @webapp2.cached_property
    def jinja2(self):
        return jinja2.get_jinja2(app=self.app)

    facebook = None
    #user = None
    csrf_protect = True

    def render_template(self, file, template_args):
        path = os.path.join(os.path.dirname(__file__), 'templates',
                            file)
        self.response.out.write(template.render(path, template_args))

    def render_json(self, response):
        self.response.write("%s(%s);" % (self.request.GET['callback'],
                                         json.dumps(response)))

    def dispatch(self):

        # Get a session store for this request.
        self.session_store = sessions.get_store(request=self.request)
        if self.request.host.find('.br') > 0:  # for a Brazilian domain that uses Portuguese
            i18n.get_i18n().set_locale('pt-br')
        else:
            lang_code = self.session.get('HTTP_ACCEPT_LANGUAGE', None)
            if not lang_code:
                lang_code = os.environ.get('HTTP_ACCEPT_LANGUAGE')
            if lang_code:
                i18n.get_i18n().set_locale(lang_code)
            lang_code_get = self.request.get('hl', None)
            if lang_code_get:
                self.session['HTTP_ACCEPT_LANGUAGE'] = lang_code_get
                i18n.get_i18n().set_locale(lang_code_get)
        try:
            # Dispatch the request.
            webapp2.RequestHandler.dispatch(self)
        finally:
            # Save all sessions.
            self.session_store.save_sessions(self.response)

    @webapp2.cached_property
    def session(self):
        # Returns a session using the default cookie key.
        return self.session_store.get_session()

    @property
    def current_email(self):
        if not hasattr(self, '_current_email'):
            self._current_email = None
            host = self.request.host
            if host.find('.br') > 0:
                email = 'Montao.com.br <[email protected]>'
            else:
                email = 'Kool Business <[email protected]>'

            self._current_email = email
        return self._current_email

    @property
    def current_host(self):
        if not hasattr(self, '_current_host'):
            self._current_host = self.request.host
        return self._current_host

    @property
    def current_logo(self):
        if not hasattr(self, '_current_logo'):
            self._current_logo = self.request.host.replace('www', '')
        return self._current_logo

    def initialize(self, request, response):
        """General initialization for every request"""
        super(Base2Handler, self).initialize(request, response)
        try:
            self.init_csrf()
            self.response.headers['P3P'] = 'CP=HONK'  # iframe cookies in IE
            # Decide the language
            if self.request.host.find('montao.com.br') > 0:
                i18n.get_i18n().set_locale('pt-br')
            elif self.request.host.find('gralumo.com') > 0:
                i18n.get_i18n().set_locale('es-ar')
        except Exception, ex:
            self.log_exception(ex)
            raise

    def handle_exception(self, ex, debug_mode):
        """Invoked for unhandled exceptions by webapp"""
        self.log_exception(ex)
        self.render('error', trace=traceback.format_exc(),
                    debug_mode=debug_mode)

    def log_exception(self, ex):
        """Internal logging handler to reduce some App Engine noise in errors"""
        msg = (str(ex) or ex.__class__.__name__) + ': \n' \
              + traceback.format_exc()
        if isinstance(ex, urlfetch.DownloadError) or isinstance(ex,
                                                                CsrfException) or isinstance(ex,
                                                                                             taskqueue.TransientError):
            logging.warn(msg)
        else:
            logging.error(msg)

    def set_cookie(
            self,
            name,
            value,
            expires=None,
            ):

        if value is None:
            value = 'deleted'
            expires = datetime.timedelta(minutes=-50000)
        jar = Cookie.SimpleCookie()
        jar[name] = value
        jar[name]['path'] = '/'
        if expires:
            if isinstance(expires, datetime.timedelta):
                expires = datetime.datetime.now() + expires
            if isinstance(expires, datetime.datetime):
                expires = expires.strftime('%a, %d %b %Y %H:%M:%S')
            jar[name]['expires'] = expires
        self.response.headers.add_header(*jar.output().split(': ', 1))

    def set_webapp2_cookie(
            self,
            name,
            value,
            expires=None,
            ):

        if value is None:
            self.response.delete_cookie(name)
        if expires:
            if isinstance(expires, datetime.timedelta):
                expires = datetime.datetime.now() + expires
            if isinstance(expires, datetime.datetime):
                expires = expires.strftime('%a, %d %b %Y %H:%M:%S')
        response.set_cookie(
            name,
            value,
            max_age=expires,
            path='/',
            domain=self.request.host.replace('www', ''),
            secure=True,
            )

    def render_jinja(self, name,
                     **data):  # if we put two stars in front of the dictionary when calling the function, the dictionary is transformed into named arguments

        logo_url = '/_/img/kool_business.png'
        if self.request.host.find('.br') > 0:
            logo_url = '/_/img/montao_small.gif'

        if not data:
            data = {}

        data['logged_in_user'] = self.current_user
        data['message'] = self.get_message()
        data['csrf_token'] = self.csrf_token
        data['user'] = self.current_user  #users.get_current_user()
        #user = users.get_current_user()
        host = self.request.host
        data['host'] = host
        data['logo'] = host.replace('www.', '').capitalize()
        data['user_url'] = \
            (users.create_logout_url(self.request.uri) if users.get_current_user() else users.create_login_url(
                self.request.uri))
        data['request'] = self.request
        data['logo_url'] = logo_url
        data['admin'] = users.is_current_user_admin()
        self.response.write(self.jinja2.render_template(name + '.html',
                                                        **data))

    def render(self, name, **data):

        logo = 'Koolbusiness.com'
        logo_url = '/_/img/kool_business.png'
        domain = 'koolbusiness'
        if not data:
            data = {}
        data['message'] = self.get_message()
        data['csrf_token'] = self.csrf_token
        data['user'] = users.get_current_user()
        data['login_url'] = users.create_login_url(self.request.uri)
        host = self.request.host
        data['host'] = host
        if host.find('.br') > 0:
            logo_url = '/_/img/montao_small.gif'

        data['logo'] = logo
        data['logo_url'] = logo_url
        data['user_url'] = \
            (users.create_logout_url(self.request.uri) if users.get_current_user() else users.create_login_url(
                self.request.uri))
        data['admin'] = users.is_current_user_admin()

        self.response.out.write(template.render(os.path.join(os.path.dirname(__file__),
                                                             'templates', name + '.html'), data))

    def init_csrf(self):
        """Issue and handle CSRF token as necessary"""

        self.csrf_token = self.request.cookies.get('c')
        if not self.csrf_token:
            self.csrf_token = str(uuid4())[:8]
            self.set_cookie('c', self.csrf_token)

            # if self.request.method == 'POST' and self.csrf_protect \
            #    and self.csrf_token != self.request.get('_csrf_token'):
            #    raise CsrfException('Missing or invalid CSRF token.')

    def set_message(self, **obj):
        """Simple message support"""
        self.set_cookie('m',
                        (base64.b64encode(json.dumps(obj)) if obj else None))

    def get_message(self):
        """Get and clear the current message"""
        message = self.request.cookies.get('m')
        if message:
            self.set_message()  # clear the current cookie
            return json.loads(base64.b64decode(message))

最佳答案

右侧滚动条上的红色凹口可以使您靠近,并且应该看到有问题的代码用红色下划线标出。将编辑器光标放在带下划线的文本上,Ctrl + 1会为您提供详细信息。

更好的是:代码->检查代码应准确显示投诉所针对的行。

缺少“自我”。在set_webapp2_cookie()中?

    response.set_cookie(

关于python - 从哪里可以导入webapp2响应类?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29658196/

10-12 02:10