Skip to content

Instantly share code, notes, and snippets.

@SebastianChristoph
Created February 4, 2025 12:05
Show Gist options
  • Save SebastianChristoph/653718138f1a4853a314da5954fd9b95 to your computer and use it in GitHub Desktop.
Save SebastianChristoph/653718138f1a4853a314da5954fd9b95 to your computer and use it in GitHub Desktop.
WebApp Flask
from flask import Flask, jsonify, request
import uuid
import credentials
app = Flask(__name__)
#diese Datei läuft auf pythonanywhere
items = {
1: {"id": 1, "name": "iPhone 13", "size": "128GB", "price": 799.99, "color": "black"},
2: {"id": 2,"name": "Samsung Galaxy S21", "size": "256GB", "price": 749.99, "color": "silver"},
3: {"id": 3,"name": "Google Pixel 6", "size": "128GB", "price": 599.99, "color": "white"},
4: {"id": 4,"name": "OnePlus 9", "size": "256GB", "price": 729.99, "color": "blue"},
5: {"id": 5,"name": "Xiaomi Mi 11", "size": "128GB", "price": 699.99, "color": "black"},
6: {"id": 6,"name": "Sony Xperia 5 III", "size": "256GB", "price": 899.99, "color": "green"},
7: {"id": 7,"name": "Motorola Edge 20", "size": "128GB", "price": 499.99, "color": "grey"},
8: {"id": 8,"name": "Nokia X20", "size": "128GB", "price": 399.99, "color": "blue"},
9: {"id": 9,"name": "Asus ROG Phone 5", "size": "512GB", "price": 999.99, "color": "black"},
10: {"id": 10,"name": "Realme GT", "size": "256GB", "price": 549.99, "color": "yellow"},
11: {"id": 11,"name": "Oppo Find X3", "size": "128GB", "price": 799.99, "color": "white"},
12: {"id": 12,"name": "Huawei P50 Pro", "size": "256GB", "price": 849.99, "color": "gold"},
13: {"id": 13,"name": "Samsung Galaxy Z Flip3", "size": "128GB", "price": 999.99, "color": "purple"},
14: {"id": 14,"name": "iPhone 12", "size": "64GB", "price": 699.99, "color": "red"},
15: {"id": 15,"name": "Google Pixel 5a", "size": "128GB", "price": 449.99, "color": "black"},
16: {"id": 16,"name": "OnePlus Nord 2", "size": "256GB", "price": 499.99, "color": "grey"},
17: {"id": 17,"name": "Vivo X60 Pro", "size": "128GB", "price": 599.99, "color": "blue"},
18: {"id": 18,"name": "Xiaomi Redmi Note 10", "size": "64GB", "price": 249.99, "color": "green"},
19: {"id": 19,"name": "Samsung Galaxy A52", "size": "128GB", "price": 349.99, "color": "white"},
20: {"id": 20,"name": "iPhone SE (2020)", "size": "64GB", "price": 399.99, "color": "black"},
}
def is_api_key_valid(api_key):
with open("/home/SebastianPythonTests/mysite/valid_api_keys.txt", "r") as file:
valid_api_keys = file.read().split(",")
return api_key in valid_api_keys
def create_api_key():
# Erzeugung eines API KEYS
new_api_key = str(uuid.uuid4())
# Überprüfen, ob es Api_Keys bereits gibt
# API-KEY der txt hinzufügen
with open("/home/SebastianPythonTests/mysite/valid_api_keys.txt", "a") as file:
file.write("," + new_api_key)
return new_api_key
@app.route("/")
def home():
return "Das ist meine WebApp."
@app.route("/is-api-key-valid")
def api_key_valid():
api_key = request.args.get("APIKEY")
result = is_api_key_valid(api_key)
if result:
return "valid"
return "not valid"
@app.route("/create-api-key")
def create_key():
password_from_url = request.args.get("PASSWORD")
if password_from_url != credentials.ADMIN_PASSWORD:
return "You are not allowed to create a API key"
new_api_key = create_api_key()
return new_api_key
@app.route("/get-all-items")
def get_all_items():
api_key = request.args.get("APIKEY")
if is_api_key_valid(api_key) == False:
return "Api key not valid. Get more informations here: www.google.de"
return jsonify(items)
# Option1 : Wert aus einer URL auslesen, kommt immer als String an
@app.route("/get-item-by-id/<id>")
def get_item_by_id(id):
api_key = request.args.get("APIKEY")
if is_api_key_valid(api_key) == False:
return "Api key not valid. Get more informations here: www.google.de"
result = items[int(id)]
return jsonify(result)
# Option2: Wert aus URL-Parameter ?parameter auslesen, zb www.shop.com/search?searchterm=handy
@app.route("/search")
def search_item():
api_key = request.args.get("APIKEY")
if is_api_key_valid(api_key) == False:
return "Api key not valid. Get more informations here: www.google.de"
searchvalue = request.args.get("searchvalue").lower()
result = [item for item in items.values() if searchvalue in item["name"].lower()]
return jsonify(result)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SHOPPY - Home</title>
</head>
<body>
<h1>Home</h1>
<p>Suche</p>
<form action="/search-results" method="POST">
<input type="text" name="searchvalue">
<input type="submit" value="Suchen">
</form>
{% for key, value in all_items_dict.items() %}
<h6>Artikelnummer: {{key}}</h6>
<a href="/product/{{key}}">{{value['name']}} ({{value['price']}}€)</a>
<hr>
{% endfor %}
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="/" method="POST">
<p>Bitte geben Sie Ihren Api-Key ein!</p>
<input type="text" name="api_key">
<input type="submit" value="OK">
</form>
{{error_message}}
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Produktinfo</title>
</head>
<body>
<h1>Produktinfo</h1>
<h4>{{product_dict['name']}}</h4>
<p>Speichergröße: {{product_dict['size']}}</p>
<p>Farbe: {{product_dict['color']}}</p>
<p>Preis: {{product_dict['price']}}€</p>
<a href="/home">Zurück zu Home</a>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Suchergebnisse</title>
</head>
<body>
<h1>Suchergebnisse</h1>
<p>Ihr Suchergebnis für: {{searchvalue}}</p>
{% for search_item in search_items_list %}
<a href="/product/{{search_item['id']}}">{{search_item['name']}} ({{search_item['price']}}€)</a>
<br>
{% endfor %}
<br>
<a href="/home">Zurück zu Home</a>
</body>
</html>
from flask import Flask, render_template, request, redirect
import requests
import json
app = Flask(__name__)
API_KEY = ""
@app.route("/", methods=["GET", "POST"])
def login():
global API_KEY
if request.method == "GET":
print("MIT GET DRAUF")
# POST
else:
print("MIT POST DRAUF")
api_key_from_user = request.form.get("api_key")
print(api_key_from_user)
result = requests.get(f"https://sebastianpythontests.pythonanywhere.com/is-api-key-valid?APIKEY={api_key_from_user}").text
if result == "valid":
API_KEY = api_key_from_user
# Weiterleitung auf home.html
return redirect("/home")
else:
return render_template("login.html", error_message = "Key not valid")
return render_template("login.html")
# fehlt noch: Fehler Handling bei falschem API Key
@app.route("/home")
def home():
all_items = requests.get(f"https://sebastianpythontests.pythonanywhere.com/get-all-items?APIKEY={API_KEY}").text
print(all_items)
all_items_dict = json.loads(all_items)
return render_template("home.html", all_items_dict=all_items_dict)
@app.route("/product/<id>")
def product_info(id):
product = requests.get(f"https://sebastianpythontests.pythonanywhere.com/get-item-by-id/{id}?APIKEY={API_KEY}").text
product_dict = json.loads(product)
return render_template("product.html", product_dict=product_dict)
# für POST requests muss man händisch den POST-Zugriff erlauben
@app.route("/search-results", methods=["POST"])
def search_results():
searchvalue = request.form.get('searchvalue')
search_items = requests.get(f"https://sebastianpythontests.pythonanywhere.com/search?searchvalue={searchvalue}&APIKEY={API_KEY}").text
print(search_items)
search_items_list = json.loads(search_items)
return render_template("search_results.html", searchvalue=searchvalue, search_items_list = search_items_list)
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment