I badly need your help. I am currently trying to pass a string value using flash but I am not sure if I got it correctly.
This is my code:
def first_view(request):
request.flash['message'] = 'Operation succeeded!'
return HttpResponseRedirect(reverse(second_view))
def second_view(request):
print request.flash['message']
request.flash.keep('message')
return HttpResponseRedirect(reverse(third_view))
I'd like to pass the message "Operation Succeeded" to second_view() through HttpResponseRedirect however I got this error message. I am new to python and django so this does not really make a clear sense to me. Your help is so much appreciated. Thanks
By default the django HttpRequest object doesn't have an attribute named flash. That's why you are getting this error. You can see available attributes here: https://docs.djangoproject.com/en/1.9/ref/request-response/#httprequest-objects
But there's no reason why you can't add one.
def first_view(request):
request.flash = {'message'] : 'Operation succeeded!'}
return HttpResponseRedirect(reverse(second_view))
def second_view(request):
try:
print request.flash['message']
request.flash.keep('message')
except:
pass
return HttpResponseRedirect(reverse(third_view))
But from where your flash.keep comes from i have no idea!! As pointed out by wtower it's more usual to rely on the django messages framework for this sort of thing.
Related
How is possible that in Python if they first check if some object is not None (if popResult:) they use that object in else branch to get its Attribute messages list?
I am not an expert for Python but I am using some already very reliable GitHub script -
https://github.com/NavicoOS/ac2git/
def TryPop(self, streamName, transaction):
logger.debug("**** entered TryPop method *******")
for i in range(0, 2):
popResult = accurev.pop(verSpec=streamName, location=self.gitRepo.path,elementList='.')
if popResult:
break
else:
logger.error("accurev pop failed:")
for message in popResult.messages:
if message.error is not None and message.error:
logger.error(" {0}".format(message.text))
else:
logger.info(" {0}".format(message.text))
return popResult
With this script I got the following error:
File "/home/ac2git/ac2git.py", line 965, in TryPop
for message in popResult.messages:
AttributeError: 'NoneType' object has no attribute 'messages'
Again - as this is one of the basic methods for this project, I really doubt that developers made such a beginner's mistake, because this project has been used in many years for migrating from some other SCM to Git, but on the other hand I really cannot see how they could use object (popResult) to retrieve its attribute if that object is None? Is it possible to put something like this in else branch?
Could you please provide me guidance for this or correction of the code if needed?
You have explicitly check if popResult is None before trying to access its members:
def tryPop(self, streamName, transaction):
logger.debug("**** entered TryPop method *******")
for i in range(0, 2):
popResult = accurev.pop(verSpec=streamName, location=self.gitRepo.path,elementList='.')
if popResult is None:
print("popResult is None !")
continue
elif popResult:
break
else:
logger.error("accurev pop failed:")
for message in popResult.messages:
if message.error is not None and message.error:
logger.error(" {0}".format(message.text))
else:
logger.info(" {0}".format(message.text))
return popResult
But actually popResult being None is just a symptom of some other error you made and the above does not cure the original cause which I'm unsure of - try using an absolute, full path for elementList.
I'm pretty new to python and just learning to ropes. In the code bellow I have a function taking several inputs from a json string. I'm attempting to have a return output in the specified strings. Problem? when I run the file I get nothing... I'm sure I'm missing something incredibly simply, but for the life of me I can't figure out what. I've attempted to use return as well as print at the end of the function. No cheese.
Help?
Here's what I've got so far:
import datetime, json
def jeeves(request): #defines the function
message=''
if request['type']=='maintainance':
message='Thank you tenant at unit'+str(request['unit'])+', your request for maintenance to deal with '+'"'+str(request['issue'])+'"'+' has been received #2 input'
elif request['type']=='purchase':
message='Thank you tenant at unit'+str(request['unit'])+'your request to purchase a'+str(request['commodity'])+ ' has been received'
elif request['type']=='reservation':
startTime=request['date'].split(" ")[1]
startTime=startTime.split('')
time=0;
num=[]
for item in startTime:
if isdigit(item):
num.append(item)
for index in range(len(num)):
time+=num[index]*10**(len(num)-index)
endTime=0
daySplit=''.join(startTime[-2:])
if time+int(request['duration'].split(' ')[0])>12:
endTime=time+int(request['duration'].split(' ')[0])-12
if daySplit=='AM':
endTime=str(endTime)+'PM'
else:
endTime=str(endTime)+'AM'
else:
endTime=endTime+int(request['duration'].split(' ')[0])
endTime=str(endTime)+daySplit
message='Thank you tenant at unit'+str(request['unit'])+'your request to reserve our '+str(request['location'])+' on '+str(request['date'].split(' ')[0])+' from '+str(request['date'].split(' ')[1])+' to '+ endTime+' has been received'
elif request['type']=='complaint':
message='Thank you tenant at unit'+str(request['unit'])+' we will have someone follow up on '+'"'+request['issue']+'"'+' in regards to our '+request['location']
return message
print message
json.dumps(jeeves({"type":"maintenance", "unit":221, "issue":"Air filter needs replacing"}))
ps: I'm new to coding in general. If there is a better, more productive way for me to ask questions, I'm open to feedback. Thank you in advanced.
You have to put return before the print function because when you use return it ends a function. You might also want to check out what return actually does here
I have a webservice that reads a JSON object and it was giving me unicodeEncodeError exception. After googling a little bit, I saw How can I convert a dict to a unicode JSON string?
(I followed other questions that were related to unicodeEncodeError but I was still getting AttributeError: 'dict' object has no attribute 'content')
I did what was mentioned in that particular question and now I am getting ..... is not JSON serializable
Can anyone tell me what do I have to do now?
Following is my code:
def someMethod()
some_data = request.data
json_string1 = json.dumps(some_data) #GETTING ERROR ON THIS LINE
json_string2 = get_string(json_string1)
archive = call.send_json(json_string2)
def get_string(value):
find_unicode = re.compile('\\\\u([\da-f]{4})')
def get_parsed_unicode(x):
return chr(int(x.group(1), 16))
return find_unicode.sub(get_parsed_unicode, str(value))
Thanks for the help !!
When you're passing the object to the method, use foo.serealize(true). Include JQUERY to use this.
I'm using Peewee and bottle.py for a very small WebApp. Once in a while I get a MySQLDatabase has gone away Error, which my script doesn't seem to recover from.
According to this answer, I should simply try-catch the error and recover myself.
An example of what I have:
def create_db_con():
return peewee.MySQLDatabase("db_name", host="host", user="user", passwd="pass")
class ModelObj(peewee.Model):
#some member ommited
class Meta:
database=create_db_con()
#route("/")
def index_htm():
try:
mo = ModelObj.filter(foo="bar")
catch OperationalError, oe:
ModelObj.Meta.database = create_db_con()
gives me the AttributeError in case of the OperationalError:
AttributeError: type object 'OrderProdukt' has no attribute 'Meta'
How am I supposed to recover from this situation?
EDIT:
As univerio pointed out, I can access it via ModelObj._meta.database, but it doesn't seem to work to just create it new.
Is this a default python behavior for nested classes?
In flask, I can do this:
render_template("foo.html", messages={'main':'hello'})
And if foo.html contains {{ messages['main'] }}, the page will show hello. But what if there's a route that leads to foo:
#app.route("/foo")
def do_foo():
# do some logic here
return render_template("foo.html")
In this case, the only way to get to foo.html, if I want that logic to happen anyway, is through a redirect:
#app.route("/baz")
def do_baz():
if some_condition:
return render_template("baz.html")
else:
return redirect("/foo", messages={"main":"Condition failed on page baz"})
# above produces TypeError: redirect() got an unexpected keyword argument 'messages'
So, how can I get that messages variable to be passed to the foo route, so that I don't have to just rewrite the same logic code that that route computes before loading it up?
You could pass the messages as explicit URL parameter (appropriately encoded), or store the messages into session (cookie) variable before redirecting and then get the variable before rendering the template. For example:
from flask import session, url_for
def do_baz():
messages = json.dumps({"main":"Condition failed on page baz"})
session['messages'] = messages
return redirect(url_for('.do_foo', messages=messages))
#app.route('/foo')
def do_foo():
messages = request.args['messages'] # counterpart for url_for()
messages = session['messages'] # counterpart for session
return render_template("foo.html", messages=json.loads(messages))
(encoding the session variable might not be necessary, flask may be handling it for you, but can't recall the details)
Or you could probably just use Flask Message Flashing if you just need to show simple messages.
I found that none of the answers here applied to my specific use case, so I thought I would share my solution.
I was looking to redirect an unauthentciated user to public version of an app page with any possible URL params. Example:
/app/4903294/my-great-car?email=coolguy%40gmail.com to
/public/4903294/my-great-car?email=coolguy%40gmail.com
Here's the solution that worked for me.
return redirect(url_for('app.vehicle', vid=vid, year_make_model=year_make_model, **request.args))
Hope this helps someone!
I'm a little confused. "foo.html" is just the name of your template. There's no inherent relationship between the route name "foo" and the template name "foo.html".
To achieve the goal of not rewriting logic code for two different routes, I would just define a function and call that for both routes. I wouldn't use redirect because that actually redirects the client/browser which requires them to load two pages instead of one just to save you some coding time - which seems mean :-P
So maybe:
def super_cool_logic():
# execute common code here
#app.route("/foo")
def do_foo():
# do some logic here
super_cool_logic()
return render_template("foo.html")
#app.route("/baz")
def do_baz():
if some_condition:
return render_template("baz.html")
else:
super_cool_logic()
return render_template("foo.html", messages={"main":"Condition failed on page baz"})
I feel like I'm missing something though and there's a better way to achieve what you're trying to do (I'm not really sure what you're trying to do)
You can however maintain your code and simply pass the variables in it separated by a comma: if you're passing arguments, you should rather use render_template:
#app.route("/baz")
def do_baz():
if some_condition:
return render_template("baz.html")
else:
return render_template("/foo", messages={"main":"Condition failed on page baz"})