Navigating through path levels of a website - python

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()

Related

why is this flask not showing standard message according to my code?

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"

Flask: Storing Socket-Connection variables without Cookies

I need to have 'variables and activity associated with each client' without using cookies. How and where can i store this variables? I am pretty new to flask and servers.
For now, I thought of using a python dictionary and storing sessionID-variable pairs like shown below.
I have a feeling that this is a stupid idea, but I can not think of an alternative :/.
Hope, you can help me.
import flask
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
enter code heresocketio = SocketIO(app)
cache = {}
#app.route('/')
def index():
return send_from_directory('static', "index.html")
#socketio.on('savePseudonym')
def sendKeepAlive():
cache[(request.sid,'pseudonym')]= pseudonym
cache[(request.sid,'time')]= time
if __name__ == "__main__":
socketio.run(app, debug=True)
You can use session, in more or less the same way you use it with Flask routes.
from flask import session
#socketio.on('savePseudonym')
def sendKeepAlive():
session['pseudonym'] = pseudonym
session['time'] = time
The only thing to keep in mind is that because Socket.IO sessions are not based on cookies, any changes you make to the session in a Socket.IO handler will not appear on the Flask session cookie. If you need to share the session between Flask routes and Socket.IO event handlers, then you can use a server-side session with the Flask-Session extension.

Exposing an endpoint for a python program

I want to expose an endpoint for a simple python program that takes in an input and manipulates it to return an output which would be the easiest approach for it.
example can be any simple python function such as:
def func(string):
string= len (string)
return tuple(int(string[i:string/2],6) for i in range (0,6,3)
It doesn't necessarily needs to be a web service. This is a microservice that can then be containerized
I need to be able to send in the i/p and receive an o/p in response communicating through the endpoint
Assuming that by input and output, you mean normal data types like int, string, etc. and by end point you mean web services: You can read about Flask . Flask allows you to create web services in python.
from flask import Flask
app = Flask(__name__)
#app.route('/end_point', methods=['GET'])
def hello():
if request.method == 'GET':
input = request.args.get('input', None)
return func(input)
def func(string): string= len (string) return tuple(int(string[i:string/2],6) for i in range (0,6,3)
if __name__ == '__main__':
app.run(host='0.0.0.0', port='8000', debug=True)
Now you can access your end point on http:\\localhost:8000\end_point?input=your_input

How to pass a variable from local flask app to remote flask app

I have two flask files. One is home.py and the other is remote.py.
The remote.py will be on another computer in LAN which acts as a server. The home.py will be in my computer.
In the home.py, i pass the url for accessing the remote.py file and if the url gets accessed,the home.py executes the route for adding two numbers and store the result in c variable and sent c to the remote.py file.
In remote.py file, I have a route for getting c value from the home system and store it in a get_c variable.
Here's the Sample Code i tried:
home.py
from flask import Flask
app = Flask(__name__)
#app.route('/sum_value_pass', methods=['POST'])
def sum_value_pass():
try:
url = '192.168.1.3:5001/sum_value_get'
if url accessed:
a = 4
b = 4
c = a + b
print(c)
# send c value to remote system
except:
print("URL offline")
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5002)
remote.py
from flask import Flask, request, jsonify
app = Flask(__name__)
#app.route('/sum_value_get', methods=['POST'])
def sum_value_get():
get_c = []
print(get_c)
# get c from home system not yet written
if __name__ == '__main__':
app.run(host='192.168.1.3', port=5001)
This is what i tried. I don't know how to pass variable between two flask app. Help me with some solutions to make it possible.
In your remote.py, does the method supported by just GET and not POST
#app.route('/sum_value_get', methods=['GET'])
def sum_value_get():
get_c = []
print(get_c)
# get c from home system not yet written
This would indeed be the correct way to go about it.
If you are needing help with sending get and post requests form your server(s),
https://www.geeksforgeeks.org/get-post-requests-using-python/ might be a good starting point

static_url_path and variable rules

Variable rules isn't working as I'd expect when static_url_path is used.
Simply, why does this work:
import flask
app = flask.Flask(__name__)
#app.route("/", defaults={"p": "")
#app.route("/<path:p>")
def main(p):
return "<h1>Hello %s</h1>" % p
if __name__ == '__main__':
app.run(debug=True)
But not this?
import flask
app = flask.Flask(__name__, static_url_path="")
#app.route("/", defaults={"p": "")
#app.route("/<path:p>")
def main(p):
return "<h1>Hello %s</h1>" % p
if __name__ == '__main__':
app.run(debug=True)
Note the added static_url_path
Some background details; I'm new to both Flask and AngularJS, but are using them here in conjunction with each other and for those not familiar with AngularJS; I'm using AngularJS to produce a single-page application in which paths are used for dynamically replacing content within a document, as opposed to reloading the whole page. Thus, I need all paths routed to the same html document (not included in the above example), ideally coming form the same function, so as to let AngularJS handle rendering as opposed to Flask.
The below answer solved that issue, but it isn't working when status_url_path is used, and I can't figure out why.
Flask route for AngularJS with HTML5 URL mode
Adding this for reference, as he is doing this exact thing.
http://www.youtube.com/watch?v=2geC50roans
You are effectively telling Flask to map /<path:static_path> to static files. That means that everything is now considered static. Don't do this!
Angular pages don't need to call into Flask static routes; keep your static routes under /static, have / produce your Angular application, then use other routes to handle Angular AJAX calls. These can have proper paths; Angular doesn't dictate what routes your Flask server will respond to.
Then keep your static route to serve the JavaScript and CSS and images, e.g. the actual static content referenced from your HTML page.

Categories

Resources