Appengine GET parameters - python

I am not really familiar with Python and am trying to transform one of my php webapps to python. Currently I am running the app on localhost using the appengine launcher and this is what I am trying to do.
I am trying to get a list of all the parameters posted to the url and then submit them to a page and get its content.
So basically:
1: get the params
2: get contents of a url by submitting those params (the PHP equivalent of curl of file_get_contents)
This is my code so far
from google.appengine.ext import webapp
class MyHandler(webapp.RequestHandler):
def get(self):
name1 = self.request.get_all("q")
name2 = self.request.get_all("input")
return name1,name2
x = MyHandler()
print x.get()
and the url
http://localhost:8080/?q=test1&input=test2
and this is the error I get
AttributeError: 'MyHandler' object has no attribute 'request'
Now I cant get it to print anything and I am not sure how I can get the contents of another url by submitting name1 and name2
I have tried looking at the documentation but I cant make sense of it since all they have is just 2 lines of code to get the use of function started.

x = MyHandler()
print x.get()
This is not a typical part of an AppEngine app. You don't use print to return output to the browser.
When you create a new app in AppEngineLauncher it gives you a skeleton project that looks like this:
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
class MainHandler(webapp.RequestHandler):
def get(self):
self.response.out.write('Hello world!')
def main():
application = webapp.WSGIApplication([('/', MainHandler)],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
Your app has to be run similarly. You need a main() method that creates a wsgi_app which is in charge of calling your handler. That main() function is called by dev_appserver, assuming your app.yaml file is set up correctly.
def get(self):
name1 = self.request.get_all("q")
name2 = self.request.get_all("input")
self.response.out.write(name1 + ',' + name2)
Should work if you've set up your app correctly.

You will need a few more lines of code to make this work if you are going to use the WebApp framework. Stick the following lines at the end of your code (and get rid of the last two lines where you instantiate your class and call the get method)
application = webapp.WSGIApplication([('/', MyHandler)])
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()

Related

Flask: How to use url_for() outside the app context?

I'm writing a script to collect the emails of those users that didn't receive an email confirmation email and resend it to them. The script works obviously outside of flask app context. I would like to use url_for() but can't get it right.
def resend(self, csv_path):
self.ctx.push()
with open(csv_path) as csv_file:
csv_reader = csv.reader(csv_file)
for row in csv_reader:
email = row[0]
url_token = AccountAdmin.generate_confirmation_token(email)
confirm_url = url_for('confirm_email', token=url_token, _external=True)
...
self.ctx.pop()
The first thing I had to do was to set SERVER_NAME in config. But then I get this error message:
werkzeug.routing.BuildError: Could not build url for endpoint
'confirm_email' with values ['token']. Did you mean 'static' instead?
This is how it's defined, but I don't think it can even find this, because it's not registered when ran as script:
app.add_url_rule('/v5/confirm_email/<token>', view_func=ConfirmEmailV5.as_view('confirm_email'))
Is there a way to salvage url_for() or do I have to build my own url?
Thanks
It is much easier and proper to get the URL from the application context.
You can either import the application and manually push context with app_context
https://flask.palletsprojects.com/en/2.0.x/appcontext/#manually-push-a-context
from flask import url_for
from whereyoudefineapp import application
application.config['SERVER_NAME'] = 'example.org'
with application.app_context():
url_for('yourblueprint.yourpage')
Or you can redefine your application and register the wanted blueprint.
from flask import Flask, url_for
from whereyoudefineyourblueprint import myblueprint
application = Flask(__name__)
application.config['SERVER_NAME'] = 'example.org'
application.register_blueprint(myblueprint)
with application.app_context():
url_for('myblueprint.mypage')
We can also imagine different ways to do it without the application, but I don't see any adequate / proper solution.
Despite everything, I will still suggest this dirty solution.
Let's say you have the following blueprint with the following routes inside routes.py.
from flask import Blueprint
frontend = Blueprint('frontend', __name__)
#frontend.route('/mypage')
def mypage():
return 'Hello'
#frontend.route('/some/other/page')
def someotherpage():
return 'Hi'
#frontend.route('/wow/<a>')
def wow(a):
return f'Hi {a}'
You could use the library inspect to get the source code and then parse it in order to build the URL.
import inspect
import re
BASE_URL = "https://example.org"
class FailToGetUrlException(Exception):
pass
def get_url(function, complete_url=True):
source = inspect.getsource(function)
lines = source.split("\n")
for line in lines:
r = re.match(r'^\#[a-zA-Z]+\.route\((["\'])([^\'"]+)\1', line)
if r:
if complete_url:
return BASE_URL + r.group(2)
else:
return r.group(2)
raise FailToGetUrlException
from routes import *
print(get_url(mypage))
print(get_url(someotherpage))
print(get_url(wow).replace('<a>', '456'))
Output:
https://example.org/mypage
https://example.org/some/other/page
https://example.org/wow/456

Adding a view.py to a flask web application

I just started working with web tools and flask.I have a python script with 9 functions and I am trying to make a flask application. the main view of this application would do the same thing as my python script (in which some functions are intermediate meaning they do not produce the final output and 2 functions produce the final output). since for one route I have 9 functions, what do you suggest? shall I rename my original script as view.py and call it in the app.py (under the corresponding route) or there is better way?
Creating a separate file is always a better choice. It will make the code more readable and understandable.
Simply create a file and call the method in app.py like this.
from flask import Flask, jsonify
from views import your_method_name
# Initialize the app
app = Flask(__name__)
# Route (e.g. http://127.0.0.1:5000/my-url)
#app.route("/my-url", methods=['POST'])
def parse():
response = your_method_name() # call the method
return jsonify(response)
if __name__ == '__main__':
app.run()

send data to html dashboard in python flask while having dictionary in a function parameter

I want to send data to html in flask framework, i have a function which receives dictionary as a parameter, then there are several functions applied on dictionary. after that final result i want to render in to html page. Its been 48 hours i am trying from different blogs but didn't get precise solution.
imports ...
from other file import other_functions
from other file import other_functions_2
from other file import other_functions_3
app = Flask(__name__, template_folder='templates/')
#app.route("/dashboard")
def calculate_full_eva_web(input:dict):
calculate_gap = other_functions(input)
calculate_matrix = other_functions_2(input)
average = other_functions_3(input)
data = dict{'calculate_gap':calculate_gap, 'calculate_matrix':calculate_matrix,'average':average}
return render_template('pages/dashboard.html', data = data)
if __name__ == "__main__":
app.run(debug=True)
TRACEBACK
Methods that Flask can route to don't take dictionaries as inputs, and the arguments they do take need to be matches by a pattern in the route. (See https://flask.palletsprojects.com/en/1.1.x/api/#url-route-registrations)
You'd get the same error if you changed
#app.route("/dashboard")
def calculate_full_eva_web(input:dict):
to
#app.route("/dashboard")
def calculate_full_eva_web(input):
Your path forward depends on how you want to pass data when you make the request. You can pass key/value pairs via URL parameters and retrieve them via the request.args object. That might be close enough to what you want. (You'll need to remove the argument declaration from calculate_full_eva_web())
Something like
from flask import request
#app.route('/dashboard')
def calculate_full_eva_web():
input = request.args
...

Python script works as pure python but not with Flask

I'm working on some code that pulls course info from Canvas. As pure python, it works fine. If I try to incorporate it with Flask, I get the following error
requests.exceptions.MissingSchema: Invalid URL 'run/api/v1/courses/1234567': No schema supplied. Perhaps you meant http://run/api/v1/courses/1234567?
This is the code in question:
Canvas file
import sys
from canvasapi import Canvas
def getinfo():
canvasurl = "https://canvas.instructure.com/";
canvastoken = #Redacted for this example
try:
canvastoken = sys.argv[1];
canvasurl = sys.argv[2];
except:
print()
#Create a new canvas object passing in the newly aquired url and token
canvas = Canvas(canvasurl, canvastoken);
#print(canv)
# Create a new course oject -- passing in course number as a parameter
# Course number is currently hard coded
print(canvas.get_course(1234567))
Flask file code (the file that I'm trying to run):
from flask import Flask
import canvas
canvas.getinfo()
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
No schema provided usually means you haven't specified the http:// or https:// in the URL.
In the code you provided, I don't see any reference to a run/api/v1/courses/1234567. One possibility is if you are using the url_for method from requests anywhere in your code, try setting _external=True:
url = url_for('relativeURL', _external=True)
This allows Flask to construct an absolute URL (i.e., a URL with domain included).
If you aren't using url_for, check other places in your code where you might be omitting the http or https from the URL.
If you update your question to include the part that refers to the offending URL, we might be able to provide more specific help.

why the print result is "favicon.ico" in web.py

I have a question about web.py.
The following is the example code from web.py tutorial. I added a print row into the code as print name. run python test.py, and then open http://0.0.0.0:8080/baby in the brower, you will see "hello baby" in the html page. However, in the terminal, you will see the print result is "favicon.ico".
I know favicon.ico, but I am pretty confused about why it doesn't print "baby".
Can someone explain this for me? Thanks to everybody~
import web
urls = (
'/(.*)', 'hello'
)
app = web.application(urls, globals())
class hello:
def GET(self, name):
print name
if not name:
name = 'World'
return 'Hello, ' + name + '!'
if __name__ == "__main__":
app.run()
Your web browser also requests favicon.ico automatically to show a small icon in your browser tab, ie:
http://0.0.0.0:8080/favicon.ico
in which case name is equal to "favicon.ico"

Categories

Resources