I want my web to be able to handle URLs inside the rule,
just like:
http://127.0.0.1:5000/tiyee?url=https://tiyee.cn/iyu2
but getting an 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.
I've tried with this code below but seems like it doesn't work
from flask import Flask, redirect
from tiyee import bypasser
app = Flask(__name__)
#app.route('/tiyee?url=<url>')
def _tiyee_redirect(url):
bypassed_json = bypasser(url)
return redirect(bypassed_json['bypassed_link'])
if __name__ == '__main__':
app.run(debug=True, port=5000)
Q: Is there a way to add URL inside the route rule?
example:
example.com/tiyee?url=https://tiyee.cn/iyu2 and get the https://tiyee.cn/iyu2
You are passing the url data in query. You will need to use request object to get the query value.
from flask import request
...
#app.route('/tiyee')
def _tiyee_redirect():
_url = request.args.get('url')
if _url is not None:
bypassed_json = bypasser(_url)
return redirect(bypassed_json['bypassed_link'])
Related
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"
I'm trying to get data from another of my servers. The other server is just an html file with "Hello World" I can reach my homepage fine, but when I go to /farmdata, I get this error:
NameError: name 'Response' is not defined"
from flask import Flask, render_template
import requests
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/farmdata')
def farmdata():
r = requests.get('http://74.114.75.91:8080')
r.url
r.encoding
return Response(
r.text,
status=r.status_code,
content_type=r.headers['content-type'],
)
if __name__== '__main__':
app.run(debug=True, port=80, host='0.0.0.0')
Edit - to anyone else with the problem, this was the solution.
from flask import Flask, render_template, Response
You have never defined Response. If you want to use flask.Response, you either have to import flask and then access it via flask.Response, or from flask import Response and then simply use Response.
In your code, you import Flask from the flask module, and that's where you get Flask from. If you remove the from flask import Flask line, you'll get a NameError complaining about Flask not being defined as well.
In Python, a name is defined if:
you defined it via variable assignment [or with a def or a class statement, which is pretty much the same] (like app in your example)
you imported it from another module explicitly (like Flask)
it's defined on startup (like list)
Is there not a " ," too much before closing the brackets of the response?
I'm trying to build a very simple API I will then fetch data from and my code looks like this:
from flask import Flask, request, jsonify
import backend as b
app = Flask(__name__)
#app.route('/api/data/', methods=['GET'])
def api():
d = {}
m = b.getMarks(b.login())
d['Marks'] = str(m)
return jsonify(d)
if __name__ == '__main__':
app.run()
When I run the app and open the web page it just says error 404 (even after typing /api/data/ in the url). Shouldn't my dictionary pop up? Sorry I'm very new to this so thanks in advance.
Also, I know for a fact that my dictionary (d) works, I printed it out.
Found the mistake: when running the API, this line
#app.route('/api/data/', methods=['GET'])
Should be replaced with this one:
#app.route('/api', methods=['GET'])
So you can just add '/api'to the url.
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)