I want to access the user_name variable outside function and class also how to do this?
Here is my Code
def DocumentCreateView(request):
user_name = request.user.email
print(user_name)
int_rep = int(rep_no)
flag = 1
count = 0
i = 1
j = 0
This is code where i want to access user_name outside class and function
path_to_piepline1 = "lazy-test/users/"+**user_name**+"/input"
print("--- first argument ---", path_to_piepline1)
You should return it:
def DocumentCreateView(request):
user_name = request.user.email
print(user_name)
int_rep = int(rep_no)
flag = 1
count = 0
i = 1
j = 0
return user_name
And then call this function:
user_name = DocumentCreateView(<pass your argument here>)
path_to_piepline1 = "lazy-test/users/"+ user_name +"/input"
If, however, you don't return it in any form (on its own or alongside other data), and it remains local, there will be no way to access it after the function returns.
Create an object of the class and use it to call the function and return the value of username.
Related
I'm building a simple blockchain/cryptocurrency to learn about python and blockchain programming.
I've run into an issue regarding appending transaction objects to the list variable 'transactions' in my Block objects.
For whatever reason, when adding a transaction to a block, it is added to every block on the chain.
I have uploaded my code to a github repo:
The project consists of 3 class files: Blockchain.py, Block.py & Transaction.py
I also have a testing file 'test1.py' which reproduces the error.
https://github.com/swooperior/blockchain-py
I suspect the issue is in the Block class file:
#Not intended behaviour. addTransaction seems to add to every block in self.chain
from datetime import datetime
import hashlib
class Block:
hash = ''
txIndex = 0
transactions = []
timeStamp = ''
previous_hash = ''
nonce = 0
def calculateHash(self):
self.hash = str(hashlib.sha256(repr([self.transactions,self.previous_hash,self.nonce]).encode('utf-8')).hexdigest())
def getHash(self):
return self.hash
def addTransaction(self,tx):
#Validate transaction, then pass to transactions list
tx.id = self.txIndex
self.transactions.append(tx)
self.txIndex += 1
def printDetails(self):
print('Block Hash: '+self.getHash())
print('Nonce: '+str(self.nonce))
print('Created: '+ str(datetime.fromtimestamp(self.timeStamp)))
print('Prev_hash: '+self.previous_hash)
print('Transactions ('+str(len(self.transactions))+'):')
self.printTransactions()
def printTransactions(self):
c = 1
for tx in self.transactions:
print('Transaction:'+ str(c))
tx.printDetails()
c += 1
def __init__(self,txlist=[],prev_hash=''):
self.txIndex = 0
self.previous_hash = prev_hash
for tx in txlist:
self.addTransaction(tx)
self.timeStamp = datetime.timestamp(datetime.now())
self.nonce = 1
self.calculateHash()
#print(self.printDetails())
The transactions attribute is a class attribute for all instances of the class. When you instantiate the class, you should create an instance variable instead. You also shouldn’t use a mutable default argument.
class Block:
...
def __init__(self, txlist=None, prev_hash=''):
self.transactions = []
txlist = txlist or []
self.previous_hash = prev_hash
for tx in txlist:
self.addTransaction(tx)
self.timeStamp = datetime.timestamp(datetime.now())
self.nonce = 1
self.calculateHash()
Function defaults are only evaluated once so each instance uses the same default argument unless you give it another one. This only happens to mutable objects as re-assigning them doesn’t copy them.
I am trying to create instances from a dataset only if they have new espn_player_id. If there is a row that has already created as an instance, I just want to execute class method.
td means total data and it is OrderedDict.
However, when it comes to else block, I keep getting an error,
'str' object has no attribute 'num_games'
How can I make td[i]['espn_player_id'] be recognized as a name of existing instance to execute num_games?
class Player:
QBR_h = None
QBR_l = 0
QBR_a = 0
ap = 0
ng = 0
def __init__(self,pid,fname,lname):
self.pid = pid
self.fname = fname
self.lname = lname
print(self.fname, self.lname,'Constructed')
def num_games(self):
self.ng = self.ng + 1
print(self.fname,self.lname,'number of games:',self.ng)
def max_QBR(self):
if self.QBR_h == None or self.QBR_h < td[i]['total_QBR']:
self.QBR_h = td[i]['total_QBR']
print(self.QBR_h)
def asdict(self):
return {'fname':self.fname, 'ng':self.ng}
lst_pid = list()
for i in range(len(td)):
print(td[i]['espn_player_id'])
if td[i]['espn_player_id'] not in lst_pid:
lst_pid.append(td[i]['espn_player_id'])
print(lst_pid)
td[i]['espn_player_id'] = Player(td[i]['espn_player_id'], td[i]['first_name'],td[i]['last_name'])
td[i]['espn_player_id'].num_games()
td[i]['espn_player_id'].max_QBR()
else:
td[i]['espn_player_id'].num_games()
td[i]['espn_player_id'].max_QBR()
Id, conf = recognizer.predict(gray[y:y+h,x:x+w]
def hour(cn):
for z in range(9,17):
if now.hour == z:
worksheet(cn, str(z)+":00")
def identify(number):
sht = gc.open("Test")
wks3 = sht.worksheet("NAMES")
b = wks3.acell('B'+str(number)).value
a = wks3.acell('A'+str(number)).value
if(Id == a and conf<65):
print(Id, conf)
Id = str(b)
Time = time.ctime()
hour(number)
elif(conf>64):
print(conf)
Id = "Unknown"
for m in range(2,100):
identify(m)
The above code is being used for facial recognition, I copied what I felt was necessary, it is not the entire code.
I'm trying create a function which I want to call back in a for loop
What am I doing wrong? I've been looking t this for 6 hours now, and anything I try doesn't seem to work.
I get a message back saying "UnboundLocalError: local variable 'Id' referenced before assignment"
It's impossible because I'm assigning with:
a = wks3.acell('A'+str(number)).value
So it grabs the ID number from the google spread sheet and checks if it is equaled to that, can someone tell me where I'm going wrong here?
def identify(number):
sht = gc.open("Test")
wks3 = sht.worksheet("NAMES")
b = wks3.acell('B'+str(number)).value
a = wks3.acell('A'+str(number)).value
#because you did, Id = ?
if(Id == a and conf<65):
print(Id, conf)
Id = str(b)
Time = time.ctime()
hour(number)
elif(conf>64):
print(conf)
Id = "Unknown"
Because you did, variable Id isn't passed as any parameter or global/local variable or as an argument to existing class.
If Id was parameter:
def identify(number,Id):
If Id was global variable:
def identify(number):
global Id
If Id was local variable:
def identify(number):
id = None # or some other data type
And if Id was argument from some class:
some_class.Id
In short you referenced Id before it was initialised. This is rookie mistake and there is some stuff where you can actually init a variable in if elif else statement but you need to trow a none of above logic of the rule.
if True: Id = 2; elif False: Id = 3; else: Id =0 #this is pseudocode, don't paste it in.
Also have in mind that next variable is also Unbound conf
EDIT:
Often to avoid this problem we write code like this:
def somefunction(parm1,parm2... ):
# global variables : description for variable stack is optional
global var1,var2 # if needed
#local variables
var3,var4 = None;
var5 = 'something else'
#in body functions : functions inside functions or just general program functions
def a(... ): return ...
#body : actually what function/program does.
# returning , finishing statement.
I am trying to loop through my One2Many records to avoid duplication.
class sales_target(models.Model):
_name = 'sales.target'
_description = 'Sales Target'
name = fields.Char(string='Name',required=True)
from_date = fields.Date(string='From Date',required=True)
to_date = fields.Date(string='To Date',required=True)
sales_team = fields.Many2one('crm.team',required=True)
sales_record_ids = fields.One2many('sales.target.record','sales_target_rec_id',string='Sales Record')
#api.one
def check_duplication(self,result):
count = 0
if self.sales_record_ids:
for record in self.sales_record_ids:
if result.id == record.sales_person_p_id:
count = 1
if count == 0:
self.write({'sales_record_ids':[(0,0,{'sales_person':result.name})]})
#api.one
def get_sales_person(self):
for res in self.sales_team.member_ids:
self.check_duplication(res)
The other class is as:
class sales_target_record(models.Model):
_name = 'sales.target.record'
sales_target_rec_id = fields.Many2one("sales.target")
sales_person = fields.Char(string='Sales Person',readonly=True,required=True)
sales_person_p_id = fields.Char(compute='get_value',store=True)
#api.onchange('sales_person')
#api.depends('sales_person')
def get_value(self):
res = self.env['res.partner'].search([('name','=',self.sales_person)])
self.sales_person_p_id = res[0].id
Now when I am hitting the button i still have duplicate records. However I tried to compare with name and things work good but I cannot compare with names since its not correct because names can be same but id cannot. That function was as:
#api.one
def check_duplication(self,result):
count = 0
if self.sales_record_ids:
for record in self.sales_record_ids:
if result.name == record.sales_person:
count = 1
if count == 0:
self.write({'sales_record_ids':[(0,0,{'sales_person':result.name})]})
Hope for guidance on this.
Can you try like this
#api.multi
def check_duplication(self,result):
if self.sales_record_ids:
for record in self.sales_record_ids:
if not result.name == record.sales_person:
self.write({'sales_record_ids':[(0,0,{'sales_person':result.name})]})
Concluding from the fact that for name it works properly, something might be wrong with your if condition.
sales_person_p_id is of type char, however you seem to compare it with an integer: result.id.
Have you made sure that both objects in your if condition are of the same type?
Try to make sales_person_p_id an integer field (e.g. via sales_person_p_id = fields.Integer(compute='get_value',store=True) or do some kind of type casting before comparing the objects.
Im trying to create an empty instance of my class object and add it to a list, however, as soon as i try to create the object add new data i get an error for it as seen below:
error
Traceback (most recent call last):
File "pagerduty.py", line 96, in <module>
UserData = User()
TypeError: 'dict' object is not callable
code
class User(object):
__attrs = ['Policy','Level', 'StartDate', 'EndDate', 'StartTime',
'EndTime', 'Name', 'Mobile']
def __init__(self, **kwargs):
for attr in self.__attrs:
setattr(self, attr, kwargs.get(attr, None))
def __repr__(self):
return ', '.join(
['%s: %r' % (attr, getattr(self, attr)) for attr in self.__attrs])
OnCallData = []
for User in objPolicyData['users']:
UserData = User()
UserData.Name = User['name']
UserData.Mobile = UserMobile = getUserMobile(User['id'])
for OnCall in User['on_call']:
UserPolicy = OnCall['escalation_policy']
PolicyName = UserPolicy['name']
if PolicyName.lower().find('test') == -1:
UserData.Policy = PolicyName
UserData.Level = OnCall['level']
UserData.StartDate = getDate(OnCall['start'])
UserData.EndDate = getDate(OnCall['end'])
UserData.StartTime = getTime(OnCall['start'])
UserData.EndTime = getTime(OnCall['end'])
OnCallData.append(UserData)
in your for scope, the User identifier is the iterated value from objPolicyData['users'] (as you used it in UserData.Name = User['name'])
you need to use a diffierent name for the iteration.
something like that:
for userI in objPolicyData['users']:
UserData = User()
UserData.Name = userI['name']
UserData.Mobile = UserMobile = getUserMobile(userI['id'])
for OnCall in userI['on_call']:
UserPolicy = OnCall['escalation_policy']
PolicyName = UserPolicy['name']
if PolicyName.lower().find('test') == -1:
UserData.Policy = PolicyName
UserData.Level = OnCall['level']
UserData.StartDate = getDate(OnCall['start'])
UserData.EndDate = getDate(OnCall['end'])
UserData.StartTime = getTime(OnCall['start'])
UserData.EndTime = getTime(OnCall['end'])
Note that using the conventions could prevent this bug for you. meaning, starting the name of a variable with lower case letter (user) and a class with capital letter (User).
this is relevant for most of your variables names
Both your class and the variable you are iterating over is called User. Change one of them to a different name.
By convention in python variable names are lowercase. So I suggest the following change:
for user in objPolicyData['users']:
user_data = User()
user_data.name = User['name']
user_data.mobile = UserMobile = getUserMobile(User['id'])
for on_call in User['on_call']:
user_policy = on_call['escalation_policy']
policy_name = user_policy['name']
if policy_name.lower().find('test') == -1:
user_data.policy = policy_name
user_data.level = on_call['level']
user_data.start_date = get_date(on_call['start'])
and so on. This follows the naming conventions in pep8. This will also take care of your error.
Of course if there is already an established style guide you should follow it and decide for a different name of User (the iteration variable).