no printing inside of "if" block - python

I have the code below in my juniper book. If user_payments is empty, i have message "no information" back. it works fine. But if rent_id is not empty, the information about user_profile (which must be printed inside of if: block, is not visible.
If I add printing user_profile after if-else block and information is exist - it shows correctly.
if not user_payments.loc[:,'powerBankRentId'].empty:
rent_id = user_payments.loc[:,'powerBankRentId'].values[0]
user_profile['rent_id'] = rent_id
user_last_rent = table_rents[table_rents['id'] == rent_id]
user_profile.append(table_rents[table_rents['id'] == rent_id].loc[:,['station_name','createdAt','endAt']])
user_profile['station_name'] = user_last_rent.loc[:,'station_name'].values[0]
user_profile['start_rent'] = user_last_rent.loc[:,'createdAt'].values[0]
user_profile['end_rent'] = user_last_rent.loc[:,'endAt'].values[0]
user_profile # doesn't print anything
else:
print('no information')
Can you give me an idea how i mush correct the code?

as it is one row dataframe, i wrote:
user_profile.head
and got expected

Related

Short description isn't working for delete selected (delete_selected.short_description isn't changing the name)

I am currently trying to change the name of the "Delete Selected" admin action. I have already effectively override the default (so I can store some data before completely deleting it), but now I want to change the option from the vague "Deleted selected" to something more specific like "Deleted all selected registrations." Or, at least, for it to say, "Deleted selected registrations" like it did before I overwrote the function.
I have so far tried this:
delete_selected.short_description = 'Delete all selected registrations'
But the option is still "Deleted selected." Is there a way to fix this?
Here's my code:
def delete_selected(modeladmin, request, queryset):
"""
This overrides the defult deleted_selected because we want to gather the data from the registration and create a
DeletedRegistration object before we delete it.
"""
for registration in queryset:
reg = registration.get_registrant()
if registration.payment_delegation:
delegate_name = registration.payment_delegation.name
delegate_email = registration.payment_delegation.email
else:
delegate_name = None
delegate_email = None
registration_to_delete = DeletedRegistration.objects.create(
registrant_name = reg.full_name(),
registrant_email = reg.email,
registrant_phone_num = reg.phone,
delegate_name = delegate_name,
delegate_email = delegate_email,
# Filtering out people (with True) who couldn't participate in events because we are only interested in the people
# we had to reserve space and prepare materials for.
num_of_participants = registration.get_num_party_members(True),
special_event = registration.sibs_event,
)
registration.delete()
delete_selected.short_description = 'Delete all selected registrations'
edit: just tried delete_selected.list_display that didn't work either
You can't have it in the function, so I just had to tab it back one space and it worked.
example:
def delete_selected(modeladmin, request, queryset)
code
delete_selected.short_description = "preferred name"
thanks.

Django - checking if instance exists results in internal server error 500

I am trying to check if I have an entry in my database using this code:
def device_update(request):
json_data = json.loads(request.body)
email = json_data['email']
imei = json_data['imei']
sdk_version = json_data['sdk_version']
date = json_data['updateDate']
rule = json_data['ruleName']
group_name = json_data['group']
if Group.objects.filter(group=group_name).exists():
print("group does exists")
else:
print("group doesn't exists")
return HttpResponse("Successful")
However, when the code reaches the if statement to check if the group exists, it returns error 500.
I tried to check with two groups one that exists and another one that doesn't, in both cases I got error 500.
How can I fix this and why is this happening?
The logic for checking if a Group exists, i.e. the line:
if Group.objects.filter(group=group_name).exists()
is not throwing the error here. It is likely that json_data is missing one of the keys you expect it to have, for example, 'group'.
I'd recommend using the get method that dictionaries have. This provides default values when the specified key is not present in the dictionary. You should also have error handling for when the request body is not in valid JSON format.
Here's an example:
def device_update(request):
try:
json_data = json.loads(request.body)
except json.JSONDecodeError:
return HttpResponse('Request body must be in valid JSON format')
email = json_data.get('email', '')
imei = json_data.get('imei', '')
sdk_version = json_data.get('sdk_version', '')
date = json_data.get('updateDate', '')
rule = json_data.get('ruleName', '')
group_name = json_data.get('group', '')
if Group.objects.filter(group=group_name).exists():
print("group does exists")
else:
print("group doesn't exists")
return HttpResponse("Successful")
I set the defaults to the empty string '', but you may want to change that.
Your view doesn't have any error handling. Looking at it quickly, at least two things could go wrong. The request body might not be valid json, and if it is valid json, it might not contain the required keys.
def device_update(request):
try:
json_data = json.loads(request.body)
except ValueError:
return HttpResponse("Invalid json")
try:
email = json_data['email']
imei = json_data['imei']
sdk_version = json_data['sdk_version']
date = json_data['updateDate']
rule = json_data['ruleName']
group_name = json_data['group']
except KeyError as e:
return HttpResponse("Missing Key %s" % e[0])
...
Writing your own validation for a single view like this is ok. As it gets more complicated, you might want to look at django rest framework. It has serializers which will help you manage validation.
Alasdair/Keselme, looks that your view is correct.
Try to put the ipdb into your code in order to debug your code, and than you can print the request.data and see what is comming in the request.

ValueError on writing lxml text

I have the following block to write an xml tag. Sometimes the name is already in the correct form (that is, it won't error), and sometimes it is not
if 'Name' in title_data:
name = etree.SubElement(info, 'Name')
try:
name.text = title_data['Name']
except ValueError:
name.text = title_data['Name'].decode('utf-8')
Is there a way to simplify this? For example, something along the lines of:
name.text = title_data['Name'] if (**something**) else title_data['Name'].decode('utf-8')
I assume that you want to avoid having to write similar code for every element you want to set. This has the smell of trying to treat the symptom rather than the cause, but if nothing else, you can simply break that out into a helper function:
def assign_text(field, text):
try:
field.text = text
except ValueError:
field.text = text.decode("utf-8")
# ...
if "Name" in title_data:
name = etree.SubElement(info, "Name")
assign_text(name, title_data["Name"] or None)

Python Geolocator Geocode location in None but still works + random string is added (weirdest error I ever saw)

I have at the moment to figure out where "favicon.ico" comes from. It is really super weird.
I use geopy to geocode a location into latitude and longitude, then I use these values to create markers on a google map (Flask GoogleMaps).
That is the piece of code:
try:
print findroomcity
location = geolocator.geocode(findroomcity)
print location, location.latitude, location.longitude
if location:
mymap = Map(
identifier="view-side",
lat=location.latitude,
lng=location.longitude,
markers=[(location.latitude, location.longitude)],
zoom = 12
)
else:
print "location is none"
In this case findroomcity is "dortmund". It is actually grabbed from a form.
If I submit the form the map is actually created, so it does not use the else block But it tells me that location in NoneType and has no attribute latitude. It seems that it calls the try block three times and the first time findroomcity is "favicon.ico", also the last time
Check the outputs of the prints:
I dont even used "favicon.ico" in my whole project, I know it must be somewhere but I checked every .py file and also searched for every print. I am really super confused, I keep searching, but maybe someone has encountered something similar.
Here is the whole method which creates the map:
# Die Filter Funktion mit Google Maps
#app.route('/<findroomcity>', methods=["GET", "POST"])
def find_room(findroomcity):
form = FilterZimmerForm()
if form.validate_on_submit():
query = Zimmer.query
filter_list = ["haustiere_erlaubt","bettwaesche_wird_gestellt","grill_vorhanden","safe_vorhanden","kuehlschrank_vorhanden","rauchen_erlaubt","parkplatz_vorhanden",
"kochmoeglichkeit_vorhanden","restaurant_im_haus_vorhanden","handtuecher_werden_gestellt","tv_vorhanden","waschmoeglichkeit_vorhanden","wlan_vorhanden"]
for filter_name in filter_list:
if getattr(form, filter_name).data:
query = query.filter(getattr(Zimmer, filter_name).is_(True))
all_rooms_in_city = query.all()
else:
all_rooms_in_city = Zimmer.query.order_by(desc("stadt")).all()
try:
print findroomcity
location = geolocator.geocode(findroomcity)
print location, location.latitude, location.longitude
if location:
mymap = Map(
identifier="view-side",
lat=location.latitude,
lng=location.longitude,
markers=[(location.latitude, location.longitude)],
zoom = 12
)
else:
print "location is none"
except AttributeError as e:
flash("Ort nicht gefunden")
print e
return redirect(url_for('index'))
except GeocoderTimedOut as e:
print e
sleep(1)
return render_template('zimmer_gefunden.html', mymap=mymap, all_rooms_in_city=all_rooms_in_city, findroomcity=findroomcity, form=form)
EDIT
I have really no idea where it comes from, I use now:
if location.latitude is not None:

storing original upload filename (web2py)

I'm attempting to do something simple and documented well, except for that it's not working on my web app.
essentally i want to save some extra attributes for the uploaded files, like original filename, email of user and also the upload date.
Now following the web2py documentation i've created this submit view. It is almost word for word copied from the documentation section here
I have a controller data.py
def submit():
import datetime
form = SQLFORM(db.uploads, fields=['up_file'], deletable=True)
form.vars.up_date = datetime.datetime.now()
form.vars.username = auth.user.email
if request.vars.up_file != None:
form.vars.filename = request.vars.up_file.filename
if form.process().accepted:
redirect(URL('data', 'index'))
elif form.errors:
response.flash = "form has errors"
and my db.py excerpt:
db.define_table('uploads',
Field('username', 'string'),
Field('filename', represent = lambda x, row: "None" if x == None else x[:45]),
Field('up_file', 'upload', uploadseparate=True, requires=[IS_NOT_EMPTY(), IS_UPLOAD_FILENAME(extension=ext_regex)]),
Field('up_date', 'datetime'),
Field('up_size', 'integer', represent= lambda x, row: quikr_utils.sizeof_fmt(x) ),
Field('notes', 'text'))
Currently the validation doesn't appear to do anything, when I submit my function, the filename isn't getting saved for some reason, and i get an error elsewhere because the value is None
You need to do something like this :
DB :
db.define_table('t_filetable',
Field('f_filename', type='string', label=T('File Name')),
Field('f_filedescription', type='text',
represent=lambda x, row: MARKMIN(x),
comment='WIKI (markmin)',
label=T('Description')),
Field('f_filebinary', type='upload', notnull=True, uploadseparate=True,
label=T('File Binary')),
auth.signature,
format='%(f_filename)s',
migrate=settings.migrate)
Controller : (default.py)
#auth.requires_login()
def addfile():
form = SQLFORM(db.t_filetable, upload=URL('download'))
if form.process(onvalidation=validate_filename).accepted:
response.flash = 'success'
elif form.errors:
response.flash = 'form has errors'
return dict(form=form)
def validate_filename(form):
if form.vars.f_filename == "":
form.vars.f_filename = request.vars.f_filebinary.filename
Function validate_filename is called AFTER the form has been validated, so form.vars should be available to use here. Function validate_filename checks if form.vars.f_filename has any value other than "" (blank) ; if not, it reads the filename from the request.vars.f_filebinary and assigns it to the form.vars.f_filename . This way you can allow users to provide an optional field for filename. If they leave it blank, and just upload the file, the f_filename in DB will be the original filename.
I tried your pasting your code into web2py to see where it goes wrong and it actually worked for me (at least the file names saved). Maybe the problem is elsewhere?

Categories