I want my python script to simultaneously accept POST variables and query string variables from the web address.
The script has code :
form = cgi.FieldStorage()
print form
However, this only captures the post variables and no query variables from the web address. Is there a way to do this?
Thanks,
Ali
cgi.parse_qsl (in any Python 2.*; urlparse.parse_qsl in 2.6 or better) take a query string and return a list of name, value pairs. Use os.environ['QUERY_STRING'] to get the query string part of the URL your CGI script was reached at (everything after the ? in the URL, if any).
Related
Context: I am creating a Django management command which will accept a positional argument. This argument is a location. My goal is to use the location value to refer to a corresponding variable.
I have a global variable named Boston_webhook. This is a simple string which contains a long URL which is just a MSteams webhook...
I have an additional global variable named Budapest_webhook which contains the same data type, but instead refers to a webhook related to the Budapest location.
In my script, a connector variable has to be defined in order to send the message to the correct place.
myTeamsMessage = pymsteams.connectorcard()
If someone entered python manage.py report Boston I want to insert this into the connector params, but I am unsure how to refer to variables dynamically.
Is it possible to refer to Boston_webhook when the location == 'Boston' using some sort of concatenation...?
something like myTeamsMessage = pymsteams.connectorcard(location + _webhook) would be ideal
I would like to avoid using conditionals as it is not scalable. I need to be able to add locations to the database without having to change code...
Use dictionary to map names of webhooks to webhooks itself - like this
webhooks = {
"Boston": "boston url",
"Budapest": "budapest url"
}
Now you can refer to your webhooks like this
# this will give you Boston webhook
myTeamsMessage = pymsteams.connectorcard(location + webhooks["Boston"])
This is simpliest way to do it. I think it would be better to create new class only for this and convert that class to string using a method , but this would be enough if you don't need anything more complex
I was able to determine a suitable solution;
myTeamsMessage = pymsteams.connectorcard(webhooks["{}".format(location)])
where the webhooks are stored in a dictionary keyed by location name.
i.e:
webhooks = {'Boston':'www.url.com',
'Budapest':'www.url1.com',
}
Thanks for the recommendations everyone!
I store in database a string with concatenated variables but when I fetch it, it behaves like string, and the variable values are not reflected.
Stored in database field I have:
"""\
Please visit the following link to grant or revoke your consent:
"""+os.environ.get("PROTOCOL")+"""://"""+os.environ.get("DOMAIN")+"""/consent?id="""+consentHash+""""""
I need to be able to fetch it in python and store it in a variable but have the concatenated variable values reflected:
someVariable = database['field']
But like this the concatenated variable values are not processed and the whole thing behaves like one string.
When I print(someVariable) I am expecting
Please visit the following link to grant or revoke your consent:
https://somedomain/consent?id=123
But instead I get the original stored string as in database field:
"""\
Please visit the following link to grant or revoke your consent:
"""+os.environ.get("PROTOCOL")+"""://"""+os.environ.get("DOMAIN")+"""/consent?id="""+consentHash+""""""
You can call eval on your string to have it, uh, evaluate the string as an expression.
Using eval is considered dangerous, because it can be used to do pretty much anything you could write code for, without knowing just what that code will be ahead of time. This is more of an issue when using it on strings provided from an outside source.
(The title may be in error here, but I believe that the problem is related to escaping characters)
I'm using webpy to create a VERY simple todo list using peewee with Sqlite to store simple, user submitted todo list items, such as "do my taxes" or "don't forget to interact with people", etc.
What I've noticed is that the DELETE request fails on certain inputs that contain specific symbols. For example, while I can add the following entries to my Sqlite database that contains all the user input, I cannot DELETE them:
what?
test#
test & test
This is a test?
Any other user input with any other symbols I'm able to DELETE with no issues. Here's the webpy error message I get in the browser when I try to DELETE the inputs list above:
<class 'peewee.UserInfoDoesNotExist'> at /del/test
Instance matching query does not exist: SQL: SELECT "t1"."id", "t1"."title" FROM "userinfo" AS t1 WHERE ("t1"."title" = ?) PARAMS: [u'test']
Python /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/peewee.py in get, line 2598
Web POST http://0.0.0.0:7700/del/test
When I view the database file (called todoUserList.db) in sqlitebrowser, I can see that these entries do exist with the symbols, they're all there.
In my main webpy app script, I'm using a regex to search through the db to make a DELETE request, it looks like this:
urls = (
'/', 'Index',
'/del/(.*?)', 'Delete'
)
I've tried variations of the regex, such as '/del/(.*)', but still get the same error, so I don't think that's the problem.
Given the error message above, is webpy not "seeing" certain symbols in the user input because they're not being escaped properly?
Confused as to why it seems to only happen with the select symbols listed above.
Depending on how the URL escaping is functioning it could be an issue in particular with how "?" and "&" are interpreted by the browser (in a typical GET style request & and ? are special character used to separate query string parameters)
Instead of passing those in as part of the URL itself you should pass them in as an escaped querystring. As far as I know, no web server is going to respect wacky values like that as part of a URL. If they are escaped and put in the querystring (or POST body) you'll be fine, though.
With Flask-wtf I want to display an error message, which should contain a HTML link to the existing profile. I need to convert the built link as string to HTML, which will be appended to the error message.
Here is an excerpt from the code:
class AddBookmarkForm(Form):
# Some Python code to define the form
def validate_bookmark_url(self, field):
if the bookmark_url exists:
bookmark_id = fetching the bookmarks id
link = 'Show bookmark?'
raise ValidationError('User already exists. ' + link)
The ouput is just a string like 'User already saved. <a href="bookmark/123456'>Show bookmark?</a>'.
How do I convert this to executable HTML inside the Python script?
I would make a few suggestions here even though I am not directly answering your exact question. The reason is that I think you should not do it the way you are trying to:
1) If a user already exists, then why do you even need to show them the URL ? Just say "This user already exists". The user who exists should already know their URL. Also, I am assuming that the url /userid needs a login first.
2) But lets say that you still want to tell the user to login, then I would rather change the code to this:
if the user_exists:
return redirect(url_for(login)) # assuming you have a view function for login.
This way, you are just asking them to login which anyway is what the end goal is in case user exists already.
This in my opinion will be a better way to do it. You don't need to worry about passing the URL in error message string. Error messages should just be simple strings as a good practice. No need to complicate them.
I'm developing application using Bottle. How do I get full query string when I get a GET Request.
I dont want to catch using individual parameters like:
param_a = request.GET.get("a","")
as I dont want to fix number of parameters in the URL.
How to get full query string of requested url
You can use the attribute request.query_string to get the whole query string.
Use request.query or request.query.getall(key) if you have more than one value for a single key.
For eg., request.query.a will return you the param_a you wanted. request.query.b will return the parameter for b and so on.
If you only want the query string alone, you can use #halex's answer.