无法在python中获取当前网址 [英] can't able to get current url in python

查看:93
本文介绍了无法在python中获取当前网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个类和方法,如下所示。我需要获取当前页面的网址。但是调用get_full_path()时出错。

I have created a class and method as like below. I need to get current page url. But am getting error while calling get_full_path().

class A(object):
   def get_user(request):
       current_url = request.get_full_path()
   return current_url


class B(A):
    b = A()
    b.get_user()
    print b.current_url


Traceback Error:
    AttributeError: 'A' object has no attribute 'get_full_path'

我犯了什么错误?

推荐答案

此代码由于某些误解而无法正常工作:

This code cannot work because has some misconceptions:


  1. 您应该将请求传递给 get_user

  2. 首先 get_user 的参数应该是 self ,它指向 A 实例。

  3. 对象无法返回值(您在 A class 返回current_url >)。

  4. 在此示例中不必使用类继承。

  1. You should pass request to get_user
  2. First argument of get_user should be self which points to A instance.
  3. Object cannot return value (you have return current_url in A class).
  4. It is not necessary to use class inheritance in this example.

您的代码应如下所示:

class A(object):
    current_url = None
    def get_user(self, request):
        self.current_url = request.get_full_path()

b = A()
b.get_user(request)
print b.current_url

或者如果您要将完整路径传递给 class A ,并且出于任何原因在继承的类B中使用它:

Or if you want to pass full path to constructor of class A, and for whatever reason use it in inherited class B:

class A(object):
    def __init__(self, current_url):
        self.url = current_url

    def get_path(self):
        return self.current_url

class B(A):
    # whatever you need here
    pass

b = B(request.get_full_path())
print b.get_path() # prints current path

这篇关于无法在python中获取当前网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆