TypeError: object.__new__() takes no parameters

本文探讨了在使用Django模板渲染时遇到类实例化错误的问题,并通过修改代码实现正确渲染。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码和错误如下:

>>> from django.template import Template,Context
>>> class Person(object):
...    def _init_(self,first_name,last_name):
...       self.first_name,self.last_name = first_name,last_name

>>> t=Template('hello,{{person.first_name}}{{person.last_name}}')
>>> c=Context({'person':Person('John','Smith')})
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: object.__new__() takes no parameters

经过折腾发现,因为Context()中对类进行了初始化,而初始化出错了。测试如下:

>>> person=Person('John','Smith')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: object.__new__() takes no parameters      
故有修改如下:

from django.template import Template,Context
>>> class Person(object):
... def _init_(self,first_name,last_name):
...       self.first_name,self.last_name = first_name,last_name

>>> t=Template('hello,{{person.first_name}}{{person.last_name}}')

>>> person=Person()
>>> person.first_name='John'
>>> person.last_name='Smith'

>>> c=Context({'person':person})
>>> t.render(c)                                                               结果正确:u'hello,JohnSmith'

import time import json import re import hashlib import requests class TSSHttpClient(object): def __init__(self, username="tapadmin", login_key="", host="127.0.0.1", port=443): self.username = username self.url_prefix = 'https://{}:{}'.format(host, port) self.auth_uri = "/skyeye/v1/admin/auth" self.logout_uri = "/skyeye/v1/admin/logout" self.init_secret(login_key) self.session = requests.Session() self.__login_process() def __login_process(self): self.__get_login_token() self.__login() def init_secret(self, login_key=""): CLIENT_ID = "mNSLP9UJCtBHtegjDPJnK3v" CLIENT_SECRET = "3460681205014671737" #生成client_secret和client_id self.client_id = hashlib.sha256((CLIENT_ID + '|' + login_key).encode()).hexdigest() self.client_secret = hashlib.sha256((CLIENT_SECRET + '|' + login_key).encode()).hexdigest() print("client_id:", self.client_id) print("client_secret:", self.client_secret) self.timestamp = str(int(time.time())) raw = '{"client_id":\"%s\","username":\"%s\"}' % (self.client_id, self.username) + '%s%s' % ( self.timestamp, self.client_secret) # 生成密钥 self.signature = hashlib.sha256(raw.encode()).hexdigest() print("signature:", self.signature) def __get_login_token(self): "发送PSOT请求获取access_token" headers = { "X-Authorization": self.signature, "X-Timestamp": self.timestamp } data = { "client_id": self.client_id, "username": self.username } requests.packages.urllib3.disable_warnings() res = self.session.post(self.url_prefix + self.auth_uri,headers=headers,data=data,verify=False) # print res.headers # print(res.text) res_dict = json.loads(res.text) token = res_dict.get("access_token", "") self.login_token = token print("free_login_token", self.login_token) print("status", res_dict.get("status")) def logout(self): params = {} self.session.request(method="get",url=self.url_prefix + self.logout_uri,params=params,verify=False) def __login(self): "GET请求获取csrf_token" params = {"token": self.login_token} res = self.session.get(self.url_prefix + self.auth_uri,params=params, verify=False) cookies = requests.utils.dict_from_cookiejar(self.session.cookies) regular_csrf_tag = re.search(r"\<meta name=\"csrf-token\" content=\"[0-9a-fA-F]*\"", res.text) regular_csrf = re.search(r"[0-9a-fA-F]{16,32}", regular_csrf_tag.group()) csrf_token = regular_csrf.group() self.csrf_token = csrf_token self.cookies = cookies def request(self, method, uri, **kwargs): requests.packages.urllib3.disable_warnings() # 添加cookie cookie = '' for name, value in self.cookies.items(): cookie += '{0}={1};'.format(name, value) headers = {'cookie': cookie} if kwargs.get("headers"): headers.update(kwargs.pop("headers")) # print(self.url_prefix + uri) res = requests.request(method=method, url=self.url_prefix + uri, headers=headers, verify=False, **kwargs) return res if __name__ == '__main__': """ :param username: 用户名 :param login_key: 分析平台-账号管理-访问配置-单点登录密钥配置 :param host: 分析平台IP :param uri: 分析平台接口 :param params: 请求参数 :return: """ try: c = TSSHttpClient(login_key="", host="", username="") method = "get" uri = "/skyeye/v1/monitor-center/situation/alarm" data = {} params = { "start_time": 170349586096, "end_time": 170349586096, "csrf_token": c.csrf_token } res = c.request(method=method, uri=uri, params=params, data=data) c.logout() ret_data = res.text print(ret_data) except Exception as e: print(e) pass 请解释这段代码需要传什么参数,为什么使用Python.exe运行会显示TSSHttpClient() takes no argents,这段代码已经运行完成没有格式,和符号错误,在使用Python.exe跑的时候,提示没有参数,为什么,为什么cmd命令去执行代码,会提示TSSHttpClient() takes no argents,不需要帮写命令代码,指出怎样去cmd中运行,是因为实际初始化值为空吗
最新发布
06-11
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值