Print web response in <code> format Google app engine python project - python

I am beginner to Google App engine. Doing a project that takes user query and print response. I used self.response.write('<code>{'+q+'}{'+str(code)+'}</code>') this way to print my response and when I read it it comes like <code>{pi}{3.14159265359}</code>. I need the response should be shown in format but tag should not come in response. How to do it.
Please conside this URL : http://ishamsample.appspot.com/eval?q=pi

You can set the response content type to, for example, text/plain:
...
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('{'+q+'}{'+str(code)+'}')
there are many different formats you can use like application/xml or application/json.

Related

python convert from request python to send api in json

guys I want to create a python API and request msg and get a response with JSON and send it to knime workflow and work with it
this is my script in python the fact is that he give me json.decoder.jsondecodeError
from importlib.metadata import files
import requests
url ='https://api.edination.com/v2/edifact/read'
headers = {'Ocp-Apim-Subscription-Key': '3ecf6b1c5cf34bd797a5f4c57951a1cf'}
files = {'file':open('C:\\Users\\hcharafeddine\\Desktop\\EDI\\Interchange_1654767219416.edi','rb')}
r = requests.post(url,files=files)
r.json()
We'll need more info to help further. I understand if you don't want to share the content of the EDI message, so here are a few things to try:
The EDINation website allows you to paste an EDI message in and it'll show you the JSON output that the API will return
It also has a sample EDIFACT document you can select and then save locally to run through your python script - you can then share the results here
You can also use HTTPToolkit to inspect the API request and response to troubleshoot further.

Write to a file on a server using python

I want to write some data, e.g. "hello" on a file that is located on a remote server, not a local server. This is the code that I used to read from server:
import urllib2
var = "hello"
url = "http://url:port/log/log.txt"
response = urllib2.urlopen(url)
txt = response.read();
print txt
As an output I was able to get the data from the log file.
Now I want to write some data, e.g. "hello" onto the same file. How to achieve that?
What your code is doing is actually not "reading a file" but sending an HTTP get request to a given url and print the HTTP response's body. What you get as content for this url is up to the HTTP server serving this url, and the fact it actually comes from a file stored on this server is totally irrelevant - it might as well come from a database, from another web server, or be typed in real time by a monkey FWIW.
If you want to use the HTTP protocol to modify the content of a given file on this server, the server must provide this service (as a given url where you're supposed to send a POST or PUT http request with the new content).

How to use flask request properly to retrieve data from JSON?

I looked many questions similar to my title but I have not found any that had same problem as me yet.
I did requests.post to post JSON to API restful server. Below is the snippet
import requests
def upload_data():
url = "http://127.0.0.1:8088/"
data = {"value":"abc123"}
response = requests.post(url, data=data)
print response.status_code, response.reason, response.text
upload_data()
And for the server side
from flask_restful import Api, Resource
from flask import request
class MyAPI(Resource):
def get():
pass
def post(self):
value = request.data['value']
response_object = {
'value':value
}
return response_object, 201
I was hoping to get the POST function to work by showing the result of 201 Created with
{
'value':'abc123'
}
But whenever I run the script, it gives me error saying that
value = request.data["value"]
TypeError: string indices must be integers, not str
I am sorry if this is a bad question but if anyone could show me what I have been missing in this script, I really appreciate it. Thank you.
That's because request data hasn't been parsed into a python dictionary. Were you perhaps thinking of
data = json.loads(request.data)
However please note that you are not actually posting a JSON body to your flask server. You are posting multipart formdata. So you may probably be looking for the answer posted by luoluo.
One the other hand if you really wanted to deal with json, The correct way to send json looks something like this:
requests.post(url, json=data)
And then the loads as suggested.
The request.data is a string, while request.values is a MultiDict.
You need update your code to :
value = request.values.get('value')
instead of
value = request.data['value']
According to the doc
args
A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).
form
A MultiDict with the parsed form data from POST or PUT requests. Please keep in mind that file uploads will not end up here, but instead in the files attribute.
values
A CombinedMultiDict with the contents of both form and args.
data
Contains the incoming request data as string in case it came with a mimetype Flask does not handle.

How to validate URL parameters in Flask

This is my first application using Flask and Python.
I am using below URL format to send a POST request from Arduino to the flask application running on Pythonanywhere server instance.
Valid POST request: 3 URL parameters
http://voyagers.pythonanywhere.com/senddata?node=1234&lat=18.5580&lng=73.8075
I need to block the request from further processing by validating the URL in some form. I want this to secure my app from un-authenticated POST requests.
Say something like this:Anything more than 3 URL Parameters
http://voyagers.pythonanywhere.com/senddata?node=324&lat=18.5580&lng=73.8075&a=c&a=d
How can I achieve this in Flask ?
Also suggest , If there is any better way which could be used to secure application from un-authorised requests.
You can get flask to validate the parameters and throw an error automatically if you are willing to switch from URL parameters (i.e. anything after the '?' symbol in the URL) to path parameters (i.e. anything that is in the Path HTTP header, or the part of the URL after the first '/' and abefore the '?').
Your example could look like this:
#app.route('/post/<int:node_id>/<float:lat>/<float:lng>', methods=['POST'])
def process_post_request(node_id, lat, lng):
# do some work
return your_result
Then you could send request to URL that would look for example like this: http://example.com/post/1234/-11.45/21.34
You can find more about this here: http://flask.pocoo.org/docs/0.12/quickstart/#variable-rules
For securing access you can use some of the example snippets here: http://flask.pocoo.org/snippets/category/authentication/
I would recommend restricting access to HTTPS only and using the basic auth if you are just playing around. This is something you can do with a simple decorator as described here: http://flask.pocoo.org/snippets/8/
You will get a prompt in your browser asking you for username and password and browser will remember it for the duration of the session. Alternatively, you can set the username and password in base64 encoded form in the Authorization header: https://en.wikipedia.org/wiki/Basic_access_authentication

How can I pass my ID and my password to a website in Python using Google App Engine?

Here is a piece of code that I use to fetch a web page HTML source (code) by its URL using Google App Engine:
from google.appengine.api import urlfetch
url = "http://www.google.com/"
result = urlfetch.fetch(url)
if result.status_code == 200:
print "content-type: text/plain"
print
print result.content
Everything is fine here, but sometimes I need to get an HTML source of a page from a site where I am registered and can only get an access to that page if I firstly pass my ID and password. (It can be any site, actually, like any mail-account-providing site like Yahoo: https://login.yahoo.com/config/mail?.src=ym&.intl=us or any other site where users get free accounts by firstly getting registered there).
Can I somehow do it in Python (trough "Google App Engine")?
You can check for an HTTP status code of 401, "authorization required", and provide the kind of HTTP authorization (basic, digest, whatever) that the site is asking for -- see e.g. here for more details (there's not much that's GAE specific here -- it's a matter of learning HTTP details and obeying them!-).
As Alex said you can check for status code and see what type of autorization it wants, but you can not generalize it as some sites will not give any hint or only allow login thru a non standard form, in those cases you may have to automate the login process using forms, for that you can use library like twill (http://twill.idyll.org/)
or code a specific form submit for each site.

Categories

Resources