Unterschiede

Hier werden die Unterschiede zwischen zwei Versionen der Seite angezeigt.

Link zu der Vergleichsansicht

Beide Seiten, vorherige Überarbeitung Vorherige Überarbeitung
Nächste Überarbeitung
Vorherige Überarbeitung
talit:flask_webserver [2023-10-02 13:37] – [HTTP-Requests an Server] scatalit:flask_webserver [2023-12-18 15:25] (aktuell) sca
Zeile 2: Zeile 2:
  
 ===== Grundgerüst ===== ===== Grundgerüst =====
 +
 +==== Übersicht ====
 +
 +Erstelle folgende Files
  
    * Flask-App `app.py` in Hauptordner    * Flask-App `app.py` in Hauptordner
    * HTML-Seite `index.html` in Unterordner `templates`    * HTML-Seite `index.html` in Unterordner `templates`
    * CSS- & JavaScript-Files `style.css` & `script.js` in Unterordner `static`    * CSS- & JavaScript-Files `style.css` & `script.js` in Unterordner `static`
 +
 +==== Setup & Ausführen ====
 +
 +   * Installiere Flask with pip
 +   * Führe `app.py` aus, dann klicke auf den Link in der Konsole und du solltest auf die Website gelangen.
 +
 +==== Files im Detail ====
  
 <code python app.py> <code python app.py>
-from flask import Flask, render_template # import the Flask object from the flask package+from flask import Flask, render_template, request, jsonify # import the Flask object from the flask package 
 +import datetime 
 +import random
  
 app = Flask(__name__) # create Flask application instance with name 'app' (name of python file) app = Flask(__name__) # create Flask application instance with name 'app' (name of python file)
-app.debug = True+#app.debug = True
  
 # HTTP REQUESTS AND RESPONSES # HTTP REQUESTS AND RESPONSES
 +# return root resource index.html for first get request "GET /"
 +@app.route('/') # '/' means that this fcn responds to request for URL /, which is main URL
 +def index():
 +    return render_template('index.html') # can also pass dictionary with data as argument: ...('index.html', data=data_dict)
 +
 +@app.route('/interactWithServer', methods = ['POST'])
 +def do_something(): # is executed whenever client sends request with "let response = await fetch('/interactWithServer', {...."
 +    data = request.json['data'] # save data sent by JS in variable
 +    # do something with data
 +    # e.g. create dictionary with response data
 +    data_response = {"name":"Johanna", "age":42}
 +    return data_response
 +
 +if __name__ == '__main__':
 +    app.run()
 +
 """ """
 typical shape typical shape
Zeile 19: Zeile 48:
 def some_fcn(): # ... regular Python function into a Flask view function which ... def some_fcn(): # ... regular Python function into a Flask view function which ...
     ...     ...
-    return ...  # ... converts the function's return value into HTTP response+    return ...  # ... converts the function's return value into an HTTP response)
 """ """
- 
-@app.route('/') # '/' means that this fcn responds to request for URL /, which is main URL 
-def index(): 
-    return render_template('index.html', data=data_dict) // returns HTML-file index.html stored in folder templates 
- 
-if __name__ == '__main__': // can run app via F5 in VSCode 
-    app.run() 
- 
 </code> </code>
  
Zeile 44: Zeile 65:
  
 <body> <body>
 +    ...
 +    <!-- can access dictionary with data that is passed as argument (see app.py above) -->
 +    <p>My data: {{ data.name_of_key }}</p>
     ...     ...
 </body> </body>
 </html> </html>
 +</code>
 +
 +Der JavaScript Code hat folgende Struktur. Im nächsten Kapitel werden die wichtigen Elemente im Detail erklärt.
 +
 +
 +<code javascript script.js>
 +// access html elements from withing JS
 +let htmlElement = document.getElementById("idOfMyHtmlElement");
 +
 +// function that interacts with flask server app
 +async function interactWithServer(word){
 +    // send post request to server
 +    let response = await fetch('/interactWithServer', {
 +        method: 'POST', // because want to send data to server s.t. it can process it
 +        headers: { // tells server that request body contains json data
 +            'Content-Type': 'application/json'
 +        },
 +        body: JSON.stringify({"name":"John", "age":41}) // data sent to server
 +    });
 +
 +    // write response status (hopefully not 404!) into console
 +    console.log(response.status); 
 +
 +    // wait for server's response, then access data sent back
 +    let json_data = await response.json();
 +
 +    // now do something with data
 +    htmlElement.innerHTML = json_data.nameOfKey;
 +}
 +
 +// function that is executed on even
 +function somethingHasHappened(event){
 +    // call function that interacts with server
 +    interactWithServer(inpPlainText.value);
 +}
 +
 +// add event listeners (clicking button, typing something into input box, ...)
 +htmlElement.addEventListener('input',somethingHasHappened)
 </code> </code>
  
Zeile 125: Zeile 187:
     return {"data": return_data} # data returned to website     return {"data": return_data} # data returned to website
 </code> </code>
 +
  
  • talit/flask_webserver.1696253858.txt.gz
  • Zuletzt geändert: 2023-10-02 13:37
  • von sca