I recently, started working on the google app engine and am facing the following problem:
I have a main.py where my user sees his own comments + those of others. Now, I need to add an EditComment.py where a user is directed when he wants to edit his code.
I am working with the guestbook application only, and to actually fetch the selected comment I need both guestbook name and the content of the comment. How do I create this url?
In other words, I need to create a url like
\edit?guestbook="Family"&content="helloworld"
I tried this
//I need to send guestbook_name and content of greeting in order to fetch the row from
//the database
//So, I show the text of the greeting and give a url to edit page
content_toSend = {'guestbook_name':guestbook_name,'content':greeting.content}
self.response.write('<blockquote>%s</blockquote>' %
(content_toSend,greeting.content))
//But the other side handler receives only the first variable of the dict in the get request
so that the user can click on a greeting and be directed to the edit page. But the get request just sends the first var(guestbook_name) in the url. How do I send the whole dictionary?
Edit : I had tired urllib.urlencode but the handler in webapp2 requires a dict and so that didn't work
The method urlencode() of urllib standard library can be useful.
edit with example:
content_toSend = urllib.urlencode({
'guestbook_name' : guestbook_name,
'content' : greeting.content
})
If you know that you are going to have these two variables in dictionary why dont u try this
self.response.write('<blockquote>%s</blockquote>' %
(content_toSend['guestbook_name'],content_toSend['content'],greeting.content))
Related
I want to add some texts into an API address in Python.
I am using requests library and the API address is:
https://one-api.ir/translate/?token={token}&action={action}&lang={lang}&q={query}
I should insert my token in {token} and in {action} section I should put google search engine and in {lang} I should put the language that I want to translate to which is fa (persian) and in last section, {query} I should put my text that I want to translate.
this is my code:
response = requests.get('https://one-api.ir/translate/?token={token}&action={action}&lang={lang}&q={query}')
response.json()['result']
How can I get an input from user and replace them instead of {token},{action},{lang} and {query}?
Have you looked at f-strings? f-strings are a way to format strings in python. https://docs.python.org/3/tutorial/inputoutput.html#fancier-output-formatting
Example:
token = "KeepThisSecret"
request = f"http://api.com/{token}/xyz"
print(request) # http://api.com/KeepThisSecret/xyz
Okay so I'm working on my project and I want the user to be able to visit other users profile so I'll have a link in the HTML page User X and I want them to be redirected to #app.route("/user/" and having user_id at the end of that path in python using flask which user_id is the 5 but that code doesn't work, is there a way to extract the number after the /user/ so when he clicks on it from an HTML page it would send him to #app.route("/user/5") and save the 5 in a variable in the python code? so later I can use the 5 in my SQL code to extract the info I need, then when he goes into the site the URL would be something.com/user/5 and the user would be able to to change the 5 to 6 in the url and it would still work taking him to a user number 6 without me having to hard-code a path to every single user?
#app.route("/user/<int:user_id>"
def users(user_id):
print(user_id) # its the url parameter - prints 5 in case of "/user/5"
if you want a variable (user id) in the path, you have to define the decorator and function as below:
#app.route("/user/<user_id>")
def user(user_id):
# your code here, with user_id being the string variable coming from the URL
I would like to get the COMPLETE URL using os.environ.
I am rendering notebooks with voila and I would like to open url from a dashboard using parameters in the URL.
So far I have:
URL_BASE = os.environ.get('SCRIPT_NAME')
PARAMETERS = os.environ.get("QUERY_STRING")
print(f'{URL_BASE=}')
print(f'{PARAMETERS=}')
assuming this is the url:
https://flyingcar.org/john/voila/render/shared/users/j/john/learn_url.ipynb?redirects=2&name=john&dossier=SA123445#{whatever=no/f=5}
URL_BASE="flyingcar.org/john/voila/render/shared/users/j/john/learn_url.ipynb"
&
PARAMETERS="redirects=2&name=john&dossier=SA123445"
Having a look at the whole collection of vars in os.environ I dont see any that would include the whole url (including what is there after #) in order to parse that part as well as with parameters.
captured_values = parse_qs(PARAMETERS)
print('here parse_qs of query:',captured_values)
>>> here parse_qs of query: {'d': ['34'], 'f': ['56']}
Some ideas?
I tried to print all the os.environ variables with:
for k,v in os.environ.items():
print(k,v)
but it nothing seems to contain what is beyond the # symbol in the URL
Any ideas?
Thanks
RELATED:
Get current URL in Python
The fragment (#) part of the URI never leaves the user agent, so it can't be picked up by the python web server. See: https://datatracker.ietf.org/doc/html/rfc3986#page-24
... instead, the fragment identifier is separated
from the rest of the URI prior to a dereference, and thus the
identifying information within the fragment itself is dereferenced
solely by the user agent, regardless of the URI scheme.
I've registered at http://www.developers.elsevier.com/action/devprojects. I created a project and got my scopus key:
Now, using this generated key, I would like to find an author by firstname, lastname and subjectarea. I make requests from my university network, which is allowed to visit Scopus (I have full manual access to Scopus search, use it from Firefox with no problem). However, I wanted to automatize my Scopus mining, by writing a simple script. I would like to find publications of an author by giving his/her firstname, lastname and subjectarea.
Here's my code:
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import json
from scopus import SCOPUS_API_KEY
scopus_author_search_url = 'http://api.elsevier.com/content/search/author?'
headers = {'Accept':'application/json', 'X-ELS-APIKey': SCOPUS_API_KEY}
search_query = 'query=AUTHFIRST(%) AND AUTHLASTNAME(%s) AND SUBJAREA(%s)' % ('John', 'Kitchin', 'COMP')
# api_resource = "http://api.elsevier.com/content/search/author?apiKey=%s&" % (SCOPUS_API_KEY)
# request with first searching page
page_request = requests.get(scopus_author_search_url + search_query, headers=headers)
print page_request.url
# response to json
page = json.loads(page_request.content.decode("utf-8"))
print page
Where SCOPUS_API_KEY looks just like this: SCOPUS_API_KEY="xxxxxxxx".
Although I have full access to scopus from my university network, I'm getting such response:
{u'service-error': {u'status': {u'statusText': u'Requestor
configuration settings insufficient for access to this resource.',
u'statusCode': u'AUTHENTICATION_ERROR'}}}
The generated link looks like this: http://api.elsevier.com/content/search/author?query=AUTHFIRST(John)%20AND%20AUTHLASTNAME(Kitchin)%20AND%20SUBJAREA(COMP) and when I click it, it shows an XML file:
<service-error><status>
<statusCode>AUTHORIZATION_ERROR</statusCode>
<statusText>No APIKey provided for request</statusText>
</status></service-error>
Or, when I change the scopus_author_search_url to "http://api.elsevier.com/content/search/author?apiKey=%s&" % (SCOPUS_API_KEY) I'm getting:
{u'service-error': {u'status': {u'statusText': u'Requestor configuration settings insufficient for access to this resource.', u'statusCode': u'AUTHENTICATION_ERROR'}}} and the XML file:
<service-error>
<status>
<statusCode>AUTHENTICATION_ERROR</statusCode>
<statusText>Requestor configuration settings insufficient for access to this resource.</statusText>
</status>
</service-error>
What can be the cause of this problem and how can I fix it?
I have just registered for an API key and tested it first with this URL:
http://api.elsevier.com/content/search/author?apikey=4xxxxxxxxxxxxxxxxxxxxxxxxxxxxx43&query=AUTHFIRST%28John%29+AND+AUTHLASTNAME%28Kitchin%29+AND+SUBJAREA%28COMP%29
This works fine from my university network. I also tested a second API Key, so have verified one with registered website on my university domain, one with registered website http://apitest.example.com, ruling out the domain name used to register as the source of your problem.
I tested this
in the browser,
using your python code both with the api key in the headers. The only change I made to your code is removing
from scopus import SCOPUS_API_KEY
and adding
SCOPUS_API_KEY ='4xxxxxxxxxxxxxxxxxxxxxxxxxxxxx43'
using your python code adapted to put the apikey in the URL instead of the headers.
In all cases, the query returns two authors, one at Carnegie Mellon and one at Palo Alto.
I can't replicate your error message. If I try to use the API key from an IP address unregistered with elsevier (e.g. my home computer), I see a different error:
<service-error>
<status>
<statusCode>AUTHENTICATION_ERROR</statusCode>
<statusText>Client IP Address: xxx.yyy.aaa.bbb does not resolve to an account</statusText>
</status>
</service-error>
If I use a random (wrong) API key from the university network, I see
<service-error>
<status>
<statusCode>AUTHORIZATION_ERROR</statusCode>
<statusText>APIKey <mad3upa1phanum3r1ck3y> with IP address <my.uni.IP.add> is unrecognized or has insufficient privileges for access to this resource</statusText>
</status>
</service-error>
Debug steps
As I can't replicate your problem - here are some diagnostic steps you can use to resolve:
Use your browser at uni to actually submit the api query with your key in the URL (i.e. copy the URL above, paste it into the address bar, substitute your key and see whether you get the XML back)
If 1 returns the XML you expect, move onto submitting the request via Python - first, copy the exact URL straight into Python (no variable substitution via %s, no apikey in the header) and simply do a .get() on it.
If 2 returns correctly, ensure that your SCOPUS_API_KEY holds the exact key value, no more no less. i.e. print 'SCOPUS_API_KEY' should return your apikey: 4xxxxxxxxxxxxxxxxxxxxxxxxxxxxx43
If 1 returns the error, it looks like your uni (for whatever reason) has not got access to the authors query API. This doesn't make much sense given that you can perform manual search, but that is all I can conclude
Docs
For reference the authentication algorithm documentation is here, but it is not very simple to follow. You are following authentication option 1 and your method should just work.
N.B. The API is limited to 5000 author retrievals per week. If you have run a lot of queries in a loop, even if they have failed, it is possible that you have exceeded that...
For future reference. OP was using the package scopus which has long been renamed to pybliometrics.
Nowadays you can do
from pybliometrics.scopus import AuthorSearch
q = "AUTHFIRST(John) AND AUTHLASTNAME(Kitchin) AND SUBJAREA(COMP)"
s = AuthorSearch(q) # handles access, retrieval, parsing and even caches results
print(s)
results = s.authors # Holds all the information as a list of namedtuples
print(results) # You can put this into a pandas DataFrame as well
I have a JS script in HTML file which collects input provided by a user. Using the inputed values I form a string and send it to backend Python script via an AJAX call:
$.ajax({
type: "POST",
url: "/cgi-bin/backend.py",
}); data: { 'form_data' : datastring}
The datastring has a value like:
age=9&country=US&buyer=Sample
I see in FireBug the same getting POSTed as:
form_data=age%3D9%26country%3DUS%26....
In my Python backend code I have a check to validate and get the CGI 'form_data' variable value:
if self.cgi.has_key ("form_data"):
But surprisingly the code does not enters this 'if' code? Also how does the values in the datastring gets changed to 'age%3D9%26'? If I split the CGI variable by '&' and the parse the splited values by '=' will I be able to get the CGI name value pairs?
First of all the data your sending is getting urlencoded and that is why it looks that way.
You will also need to post your python code if you need any more help with this question. That aside I would advice you to use a python web framework such as Flask or bottle instead of using cgi.