Let's assume my code is like this:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
#app.route('/test')
def test():
# Get HTML contents of route "/"
return "test"
if __name__ == '__main__':
app.run()
Now in the test function, I want to get the HTML content of the route / (which is Hello World!) programatically. Is there a way to do this ? Note that I don't want to use a library like request to do that because in my original use case both the route functions are authenticated and using a library like request will just show "Access not allowed" error.
It's just a function, you can call it.
def test():
hello = hello_world()
However, if you have content you want to show in more than one handler, you should probably extract it into a separate function that you can call from both routes.
Related
I am working on a website where we have different levels and sublevels. Is it possible to generate the sublevels on the fly based on level clicked.
I am working with it in a flask application.
Note : Website is connected to google analytics and has multiple levels and is impossible to do it manually.
str.split('/') should do the trick, when used with Flask's request. Request's path holds the part after www.example.com/
Simple example. Note the empty first result in the returned list
from flask import Flask, request
app = Flask(__name__)
#app.route('/')
def main():
return 'Hello'
#app.route('/path/to/wherever')
def example():
for p in request.path.split('/'):
print(p)
return str(request.path.split('/'))
if __name__ == "__main__":
app.run()
my rest service sits at http://127.0.0.1:5000, but when i launch it, it gives me 404:
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
why is that? I want my server to show some status msg like 'service ready'.
The actual function that i will use is accessible and works, when i press 'http://127.0.0.1:5000/parser/tengrinews' and hit enter it outputs the msg i coded in the function in my flask app:
[
"parsing this website :",
"tengrinews"
]
the main code:
from flask import Flask
import requests
from datetime import datetime
from flask import jsonify
app = Flask(__name__)
#this is my std method i can't see
#app.route("/http://127.0.0.1:5000/", methods = ['GET'])
def main():
return jsonify('service is ready')
#app.route("/parser/<string:website>", methods = ['GET'])
def parse(website):
return jsonify("parsing this website :", website )
if __name__ == "__main__":
app.run(debug=True)
Change this line -
#app.route("/http://127.0.0.1:5000/", methods = ['GET'])
to
#app.route("/", methods = ['GET']).
Because you have to specify only the extended URL that will be used. The #app.route decorator handles the rest for us
Note* (Don't do this. For fun only) -
If you wish to continue to use #app.route("/http://127.0.0.1:5000/", methods = ['GET']) then access the endpoint with the url - http://localhost:5000/http://127.0.0.1:5000/. You will get the response as "service is ready"
the api should include one function called "write text to file" and inputs a string parameter
as for the function to write to the disk I have no problem and I implemented the code my problem is how to set the rest API using python.
EDIT:
this is my code:
from flask import (
Flask,
render_template
)
import SocketServer
import SimpleHTTPServer
import re
app = Flask(__name__, template_folder="templates")
#app.route('/index', methods=['GET'])
def index():
return 'Welcome'
#app.route('/write_text_to_file', methods=['POST'])
def write_text_to_file():
f = open("str.txt", "w+")
f.write("hello world")
f.close()
if __name__ == '__main__':
app.run(debug=True)
anyhow when I try to test my rest api:
http://127.0.0.1:5000/write_text_to_file
I am getting the following error:
Now I'm trying to test my rest-api , however how can I make my code to start the server and to the test the post request api, this is my test_class:
import requests
import unittest
API_ENDPOINT="http://127.0.0.1:5000/write_text_to_file"
class test_my_rest_api(unittest.TestCase):
def test_post_request(self):
"""start the server"""
r = requests.post(API_ENDPOINT)
res = r.text
print(res)
also when runnning my request using postman I am getting internal_server_error:
You're doing a GET request for this url, but you've specified that this endpoint can only accept POST:
#app.route('/write_text_to_file', methods=['POST'])
Also, the SocketServer and SimpleHTTPServer imports are not needed with Flask.
The method is not allowed because Chrome (or any browser) makes GET requests.
Whereas, you defined it as POST
#app.route('/write_text_to_file', methods=['POST'])
Either change it to a GET method, or use a tool such as POSTMan to perform other HTTP call types
I started learning Flask framework recently and made a short program to understand request/response cycle in flask.
My problem is that last method called calc doesn't work.
I send request as:
http://127.0.0.1/math/calculate/7/6
and I get error:
"Not Found:
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again."
Below is my flask app code:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return "<h1>Hello, World!</h1>"
#app.route('/user/<name>')
def user(name):
return '<h1>Hello, {0}!</h1>'.format(name)
#app.route('/math/calculate/<string:var1>/<int:var2>')
def calc(var1, var2):
return '<h1>Result: {0}!</h1>'.format(int(var1)+int(var2))
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80, debug=True)
To access request arguments as described in your comment you can use the request library:
from flask import request
#app.route('/math/calculate/')
def calc():
var1 = request.args.get('var1',1,type=int)
var2 = request.args.get('var2',1,type=int)
return '<h1>Result: %s</h1>' % str(var1+var2)
The documentation for this method is documented here:
http://flask.pocoo.org/docs/1.0/api/#flask.Request.args
the prototype of the get method for extracting the value of keys from request.args is:
get(key, default=none, type=none)
I am trying to get the flask framework to work with Facebook. I'm doing this with flask_canvas. I followed the example for flask_canvas in the documentation (found here: http://flask-canvas.readthedocs.org/en/latest/) but I keep getting the following error:
AssertionError: View function mapping is overwriting an existing endpoint function: inner
If I comment out the method user(), it will run, but when that method is not commented out, I get the above error.
Any idea how to make it so I can have both the canvas() and user() methods without getting an AssertionError thrown?
import flask_canvas
from flask import Flask, session, redirect
app = Flask(__name__)
flask_canvas.install(app)
HOST = 'localhost'
PORT = 8000
#app.route('/')
def hello_world():
return 'Hello World!'
# route your canvas-specific page
#app.canvas_route('/app/', methods=['GET','POST'])
def canvas():
return 'hello, world'
#route page requiring user data
#app.canvas_route('/user/', methods=['GET','POST'])
def user(canvas_user):
return canvas_user.request('/me')
if __name__ == '__main__':
app.run(host = HOST, port = PORT, debug = True)
I had a similar issue, using a decorator without #wraps renames the function being decorated. See this for details http://flask.pocoo.org/docs/patterns/viewdecorators/
I encountered this problem, I think there may be two or more inner function in your app.
#app.route('/show1',methods=['GET','POST'])
def show():
return redirect(url)
#app.route('/show2',methods=['GET','POST'])
def show():
return redirect(url)
this will tell you an error:
AssertionError: View function mapping is overwriting an existing endpoint function: show