Why is Django shell running a function using not the inputted parameters? - python

I have a function that is supposed to update Django objects, which each have two date fields, named "production" and "development". The function reads from a python object, containing a list of Django objects along with their new dates, as well as a single label indicating for the entire list whether the fields to be updated are "production" or "development".
For testing, I have two python objects, containing two different lists of django objects and dates, one for "production" and one for "development". When I call the function on one of these objects, no matter what, it's the list and dates in the "production" object that get updated, though whether the info goes to the "development" or "production" fields in those django objects still depends on the label of the initial python object being called on. I have no idea why this is happening.
Python class and initialization of two python objects:
import pytz
import datetime
class timess():
#Reflects update statuses for the two servers
lists = {
"none" : [],
"uploaded" : [],
}
servername = ""
def __init__(self, nonay, uplay, servertype):
self.lists["none"] = nonay
self.lists["uploaded"] = uplay
self.servername = servertype
timezone = pytz.timezone("America/Chicago")
d1 = datetime.datetime(1999, 8, 12, 12, 32, 41)
d2 = datetime.datetime(1996, 8, 12, 12, 32, 41)
d3 = datetime.datetime(2004, 8, 12, 12, 32, 41)
d1a = timezone.localize(d1)
d2a = timezone.localize(d2)
d3a = timezone.localize(d3)
p1 = datetime.datetime(1997, 8, 12, 12, 32, 41)
p2 = datetime.datetime(2002, 8, 12, 12, 32, 41)
p3 = datetime.datetime(2006, 8, 12, 12, 32, 41)
p4 = datetime.datetime(1992, 8, 12, 12, 32, 41)
p1a = timezone.localize(p1)
p2a = timezone.localize(p2)
p3a = timezone.localize(p3)
p4a = timezone.localize(p4)
dnonay = [
("mvol/0004/1905/0404", None),
("mvol/0004/1920/1111", None),
("mvol/0004/1930/0812", None),
("mvol/0004/1905/0214", None),
("mvol/0004/1930/1001", None),
("mvol/0004/1905/0917", None),
("mvol/0004/1930/0712", None),
("mvol/0004/1920/1202", None),
]
duplay = [
("mvol/0004/1905/0130", d1a),
("mvol/0004/1920/0624", d2a),
("mvol/0004/1930/0311", d3a),
]
dtimess = timess(dnonay, duplay, "development")
pnonay = [
("mvol/0004/1905/0130", None),
("mvol/0004/1920/1111", None),
("mvol/0004/1905/0214", None),
("mvol/0004/1930/0311", None),
("mvol/0004/1905/0917", None),
("mvol/0004/1930/0712", None),
("mvol/0004/1920/0624", None)
]
puplay = [
("mvol/0004/1905/0404", p1a),
("mvol/0004/1920/1202", p2a),
("mvol/0004/1930/0812", p3a),
("mvol/0004/1930/1001", p4a),
]
ptimess = timess(pnonay, puplay, "production")
Function definitions:
from listpage.timess import *
from listpage.models import *
def integratetimess(timess):
'''
Takes information in server update list and applies it
to mvolFolder objects in site. Does not work properly.
'''
if timess.servername == "development":
for line in timess.lists["uploaded"]:
target = mvolFolder.objects.get(name = line[0])
target.dev = line[1]
target.save()
if timess.servername == "production":
for line in timess.lists["uploaded"]:
target = mvolFolder.objects.get(name = line[0])
target.pro = line[1]
target.save()
def integrateot(namey, date, servertype):
'''
This function works when called on
a django mvolFolder object outside of the
timess object
'''
target = mvolFolder.objects.get(name = namey)
if(servertype == "development"):
print(namey)
print("development, initially:")
print(target.dev)
print(target.pro)
target.dev = date
print("development, after changing")
print(target.dev)
print(target.pro)
target.save()
if(servertype == "production"):
print(namey)
print("production, initially:")
print(target.dev)
print(target.pro)
target.pro = date
print("production, after changing")
print(target.dev)
print(target.pro)
target.save()
def integratetimesx(timess):
'''
However, when integrateot is called to loop on the
list in the python object, there's the same issue
as the first function
'''
for line in timess.lists["uploaded"]:
integrateot(line[0], line[1], timess.servername)
Django object model:
from django.db import models
# Create your models here.
class Folder(models.Model):
name = models.CharField(max_length = 19)
def __str__(self):
return self.name
class mvolFolder(Folder):
date = models.DateTimeField(null = True)
valid = models.NullBooleanField(null = True)
dev = models.DateTimeField(null = True)
pro = models.DateTimeField(null = True)
parent = models.ForeignKey('self', on_delete=models.CASCADE, null = True, related_name = 'children')
Django shell input:
from listpage.models import mvolFolder
from listpage.timess import *
from listpage.convtimess import *
integratetimesx(ptimess)
integratetimesx(dtimess)
Python 3.7.0
Django 2.0.8
Windows 10 Enterprise Version 1803

I could be wrong, the question is a little vague and you never give an exact description of the problem, but it looks to me to be a python problem not a django one. The timess class has a class attribute called lists which you are treating as an instance attribute. Here's a concise description of the difference in a similar case. For a timess instance, self.list is a local reference to the class dictionary. Calling timess(...) changes the value in the class dictionary, so it's changed for all instances. I won't comment on the rest of the code, but to make this class work as (I think) you expect, try this instead:
class timess():
def __init__(self, nonay, uplay, servertype):
self.lists = {
"none" : [nonay],
"uploaded" : [uplay],
}
self.servername = servertype

Related

Locust - Shape Class ignored when running Web UI with --class-picker

I saw that locust supports defining different user classes and shape classes and that it is possible to choose which one to run through the web-ui when locust is started with --class-picker
However, when I select a user class and a shape class, locust doesn't use the shape and uses only what I type in the "Number of Users" and "Spawn rate" fields on the interface.
How can I make locust use the selected shape file?
This is how my user classes look: (the other user classes are very similar to this one)
from locust import HttpUser, TaskSet, task
from locust import LoadTestShape
import csv
import random
class Tasks1(TaskSet):
DATA = {}
def on_start(self):
if not self.DATA:
self._get_pics()
def _get_pics(self):
with open('targets.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',', quotechar="'")
for row in csv_reader:
self.DATA['images/' + row[0]] = '{"x":' + row[1] + ',"y":' + \
row[2] + ',"width":' + row[3] + ',"height":' + row[4] + '}'
#task
def service(self):
key = random.choice(list(self.DATA.keys()))
payload = {self.DATA[key]}
with open(key, 'rb') as image:
self.client.post('/process', headers={'Authorization': 'Bearer ' + token, 'Accept-Encoding': 'gzip'}, files={'image': image}, data=payload)
#task
def stop(self):
self.interrupt()
class FirstUser(HttpUser):
tasks = [Tasks1]
And these are the shape classes:
ShapeClass1.py:
from locust import LoadTestShape
class ramp_up_20min_40users_hold_5min_ramp_down_5min_1user(LoadTestShape):
stages = [
{"duration": 1200, "users": 40, "spawn_rate": 0.034},
{"duration": 300, "users": 40, "spawn_rate": 1},
{"duration": 300, "users": 1, "spawn_rate": 0.0325}
]
def tick(self):
run_time = self.get_run_time()
for stage in self.stages:
if run_time < stage["duration"]:
try:
tick_data = (
stage["users"], stage["spawn_rate"], stage["user_classes"])
except:
tick_data = (stage["users"], stage["spawn_rate"])
return tick_data
return None
ShapeClass2.py:
from locust import LoadTestShape
class ramp_up_1min_40users_hold_20min(LoadTestShape):
stages = [
{"duration": 60, "users": 40, "spawn_rate": 0.67},
{"duration": 1200, "users": 40, "spawn_rate": 1},
]
def tick(self):
run_time = self.get_run_time()
for stage in self.stages:
if run_time < stage["duration"]:
try:
tick_data = (
stage["users"], stage["spawn_rate"], stage["user_classes"])
except:
tick_data = (stage["users"], stage["spawn_rate"])
return tick_data
return None
I can see the choices in the UI.
However, the Number of users and spawn rate field are not disabled and locust executes what I type in there and not what is defined in the load shape files.
Am I missing something here?

Import CSV script- make python 2.7 compatible

I created the following script to import files into my django models. It works fine, but only when using python 3.4.
How can I change this script to make it run on 2.7?
Thanks,
Error:
Traceback (most recent call last):
File "update_fromcsv.py", line 18, in <module>
l = list(csv.reader(open('test_data.csv', encoding='utf-8', errors='ignore')))
TypeError: 'errors' is an invalid keyword argument for this function
My import file:
import sys, os
import django
sys.path.append('/srv/apps/stashdDB/code')
os.environ['DJANGO_SETTINGS_MODULE'] = 'stashdDB.settings'
django.setup()
import stashd.models as m
import csv
l = list(csv.reader(open('test_data.csv', encoding='utf-8', errors='ignore')))
Gender_CHOICES = {
'Male': 1,
'Female': 2,
'Unisex': 3,
}
Stock_CHOICES = {
'in stock': 1,
'low stock': 2,
'out of stock': 3,
'discountinued': 4
}
for i in l[1:]:
cat = m.Category.objects.get_or_create(category_name = i[4])[0]
prod = m.Product(
name = i[0],
link = i[1],
description = i[6],
brand = i[7],
gender = Gender_CHOICES[i[8]] if i[8] in Gender_CHOICES else 3,
store = m.Store.objects.get_or_create(store_name = i[2])[0]
)
prod.save()
var = m.Variation(
product = prod,
variation = "default"
)
var.save()
img = m.Image(
variation = var,
image = i[5]
)
img.save()
size = m.Size(
variation = var
)
size.save()
price = m.Price(
variation = var,
price = float(i[3])
)
etc....
l = list(csv.reader(open('test_data.csv', 'rb')))

id type in mongoengine objects

I use mongoengine and when I call a class mongoengine give me error
for example when I use : Site.objects()
I get this
TypeError: id must be an instance of (str, unicode, ObjectId), not <type 'dict'>
and it's my class definition :
class Site(db.Document):
siteURL = db.URLField('''required = True''')
name = db.StringField(required = True)
pages = db.ListField(ReferenceField(Page))
siteId = db.IntField(required = True , unique = True )
views = db.IntField(required = True , default = 0)
visitors = db.IntField(required = True , default = 0)
stat_by_hour = LimitedListField(EmbeddedDocumentField(HourStat))
weekday_stat = db.ListField(EmbeddedDocumentField(WeekdayStat))
os = db.ListField(ReferenceField(OS))
countries = db.ListField(ReferenceField(Country))
cities = db.ListField(ReferenceField(City))
browsers = db.ListField(ReferenceField(Browser))
resolutions = db.ListField(ReferenceField(Resolution))
mostVisitedDays = db.SortedListField(EmbeddedDocumentField(MostVisitedDay) , ordering="visitors")

How do I lock these attributes?

I've only just started coding, so I thought I would try and make something simple, however, I can't select the objects from my ls, I know the error is in my def attrLockT and was wondering if anyone could help me to fix this issue and understand what I am doing wrong?
import maya.cmds as cmds
#Selects the attributes
sat = ['.tx', '.ty', '.tz']
sar = ['.rx', '.ry', '.rz']
sas = ['.sx', '.sy', '.sz']
#Creates the list of currently selected objects
myList = cmds.ls(sl = True)
#Lock the translate attributes of the selected objects
def attrLockT(*args):
checkAttr=cmds.getAttr (myList[0] + sat)
if (checkAttr == 0):
cmds.setAttr(myList[0] + sat, lock = 1)
#Delete window if it is already open
if cmds.window('animationCtrl', exists=True):
cmds.deleteUI('animationCtrl', window=True)
#Setup the window
cmds.window(
'animationCtrl',
title = "Animation Controls",
widthHeight = (300, 500),
s = False)
form = cmds.formLayout()
tabs = cmds.tabLayout(innerMarginWidth=5, innerMarginHeight=5)
cmds.formLayout(
form,
edit=True,
attachForm=(
(tabs, 'top', 0),
(tabs, 'left', 0),
(tabs, 'bottom', 0),
(tabs, 'right', 0)))
#Layout for the first tab
child1 = cmds.gridLayout( numberOfRowsColumns=(4, 3) , cwh = (100, 50))
cmds.text(label = "")
cmds.text(label = "Lock", align = "center", h = 20, w = 250)
cmds.text(label = "")
cmds.button(label = "Translate", h = 300, w = 250, c = attrLockT)
cmds.button(label = "Rotate", h = 50, w = 250)
cmds.button(label = "Scale", h = 50, w = 250)
cmds.text(label = "")
cmds.text(label = "Unlock", align = "center", h = 20, w = 250)
cmds.text(label = "")
cmds.button(label = "Translate", h = 50, w = 250)
cmds.button(label = "Rotate", h = 50, w = 250)
cmds.button(label = "Scale", h = 50, w = 250)
cmds.setParent( '..' )
#Layout for the second tab
child2 = cmds.rowColumnLayout(numberOfColumns=3)
cmds.button()
cmds.button()
cmds.button()
cmds.setParent( '..' )
cmds.tabLayout(
tabs,
edit=True,
tabLabel=((child1, 'Lock/Unlock'), (child2, 'Keyable/Unkeyable')))
cmds.showWindow('animationCtrl')
The error that is thrown is
# Error: coercing to Unicode: need string or buffer, list found
# Traceback (most recent call last):
# File "<maya console>", line 16, in attrLockT
# TypeError: coercing to Unicode: need string or buffer, list found
Does this work?
myList[0] + sat
Is myList[0] type of list ? Because the sat variable is certainly list.
If myList is just a list of string then myList[0] will be just one element of type string and it will produce an error.
Simplify your program, just leave only locking routine and window with button to see what will happen, be sure that the right name of an object + attribute is passed to getAttr - just string like 'obj.attrib'.
Some python specific clues for your function
If you need to sum two lists:
[ objName + attName for objName, attName in zip(myList, sat) ]
that will result, for example, in ['obj1.tx', 'obj2.ty', 'obj3.tz']
If you need apply a list of attributes to an object:
[ myList[0] + a for a in sat ]
that will result in ['obj1.tx', 'obj1.ty', 'obj1.tz']
If you need apply the same list of attributes to all objects:
[ objName + attName for objName in myList for attName in sat ]
will result in ['obj1.tx', 'obj1.ty', 'obj1.tz', 'obj2.tx', ..., 'obj3.tz']
Then you can call your locking function over that result list:
def locker(a):
checkAttr = cmds.getAttr(a)
if (checkAttr == 0):
cmds.setAttr(a, lock = 1)
and finally it should look:
def attrLockT(*args):
atrlist = [ ..... ]
for a in atrlist:
locker(a)
Two issues:
first, you want to loop through the individual attributes and concatenate them with object names:
def lockTranslate(*args):
for obj in mylist:
for attr in ['.tx', '.ty', '.tz']:
cmds.setAttr(obj + "." + attr, l=True)
second, and maybe more important, you will likely have problems the scope of your functions. In the form you have it typed in, variables like myList and sat, etc are accessible to the function through closure - it will work if you execute all of this in the listener, but if you break the closure (for example, if this goes into a function that gets called by another function) things wont work -- myList will be stuck pointing at whatever was selected when the function was defined.
In this particular case you probably want to just operate on selection instead of inheriting myList:
def lockTranslate(*args):
for obj in cmds.ls(sl=True, type = 'transform'):
for attr in ['.tx', '.ty', '.tz']:
cmds.setAttr(obj + "." + attr, l=True)

django point definition

my models:
class Mod(models.model)
name = models.CharField(max_length = 255)
co_x = models.DecimalField(max_digits = 11, decimal_places = 8)
co_y = models.DecimalField(max_digits = 11, decimal_places = 8)
my views:
def closedPoint(request):
location_name = str(request.POST.get("lo", default=""))
nokta_x = int(float(request.POST.get("x"))
nokta_y = int(float(request.POST.get("y"))
poi = Point(nokta_x, nokta_y, srid = 900913)
sk = Mod()
poi_s = Point(sk.co_x, co_y, srid = 900913)
resut_poi = Mod.objects.filter(poi_s__distance_lte = (poi, D(km = 7))).filter(name__in = location_name)
here i want to deduct closest point in 7 km but it gives "Invalid parameters given for Point initialization
Ok, so it's now clear your error message comes from initializing a Point class with None.
That is your first critical problem.
Judging by the error message, my guess is that poi_s is initialized with None, None as Mod() is an unsaved instance with no values and those are the invalid parameters.
sk = Mod() # unsaved Mod instance with no defaults
poi_s = Point(sk.co_x, co_y, srid = 900913)
# sk.co_x is None
Your second problem that will appear after fixing the above is querying a model with an invalid lookup type (specific to PointField, __distance) which accepts a tuple. How to solve that, I don't know.
You would have to look at how GeoDjango translates that tuple into a DB lookup.

Categories

Resources