Python Flask Programming Fundamentals

Suppressor

Uzman üye
Katılım
16 Kas 2022
Mesajlar
1,269
Çözümler
29
Tepkime puanı
914
p0qbke2.png


Hello everyone, I am Suppressor. Today, I will introduce you to Flask, a micro web framework of Python.

umBqNLP.png


Flask is a simple and lightweight micro web framework used for web development and web applications under the Python programming language. The reason it's called a "micro" web framework is due to its minimal and lightweight structure. Flask provides developers with only the essential tools and can be extended with various libraries when more complex features are needed.

How-to-Create-an-API-Using-The-Flask-Framework-1024x576.png

Flask URL Structure and Routing

Looking at the basic structure and routing of Flask, in the simplest explanation, a request is sent from our computer to our application, and the response to the request is displayed in our browser. When we start a Flask application, it also sets up a server at a local address and we continue our operations from there. Flask automatically determines this address and shows it to us when we start the application.



request-response.jpeg


Routing and Syntax

Syntax:
  • Task: app.route
  • Define Function: def route():
  • Task: return "Hello"
Generally, the syntax is like this:

Python:
from flask import Flask

app = Flask([B]name[/B])

@app.route("/")def route():return "Hello"

if [B]name[/B] == "[B]main[/B]":app.run()

Adding the Flask library to the program and creating a Flask object:

Python:
from flask import Flask

app = Flask([B]name[/B])

Next, we tell Flask which function to run when a certain event occurs using the "route" decorator (decorators are special functions in Python):

Python:
@app.route("/")def route():return "Hello"

At this point, when we go to the root directory, meaning the main URL, we will get a response like "Hello".

Another example is from the /admin directory.

Templates

Templates are structures that exist to interpret languages like HTML, CSS, JS in your browser and display them to the user. As you saw above, we could only place string expressions on the screen. However, using templates, we can have our HTML, CSS, and JavaScript codes interpreted by the browser. Before moving on to the coding phase, we need to create a folder named "templates" in the directory where our Flask application is located. By default, Flask pulls the templates it will interpret from this folder. Then, I create a file named "index.html" inside it. Additionally, you need to include render_template in the library part. You can see it in the code below.

Python:
from flask import Flask, render_template

app = Flask([B]name[/B])

@app.route("/template")def index():return render_template('index.html')

if [B]name[/B] == "[B]main[/B]":app.run(debug=True)

If we want to show an HTML file to the user, we use the render_template() function and write the name of the HTML file we want from the "templates" folder.

Example HTML Code:

HTML:
<!DOCTYPE html>

<html lang="tr"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Arge Team</title>    <script src="https://cdn.tailwindcss.com"></script></head><body><style>    body {        background-color: black;        text-align: center;        font-style: italic;    }    h6 {        color: rgb(220 38 38);    }    p {        color: rgb(132 204 22);    }</style>    <p>Flask</p>    <br>    <h6>Template</h6></body></html>

Sending Data from Flask Application to HTML File

Jinja Syntax

Conditional Statements and Loops

For loops, conditional statements, etc.:

For showing variables:

We learned above how to display the index file to the user. But what if we need to send data from a Flask application we wrote to the user? Let's first look at how to do this.

Again, write the codes I wrote above and similarly write render_template('index.html'). But this time, there's a difference: you can write any name you want, but you need to give one parameter. The name doesn't matter; I gave the parameter name "sayı".

You can define this in the upper lines or directly here:

ctf0sk9.png


Python:
return render_template("index.html", sayı=15)

On the HTML side, you need to specify this variable name inside {{ parameter_name }}.

Examples

Control if a number exists and display it in HTML:

Python:
from flask import Flask, render_template

app = Flask([B]name[/B])

@app.route("/")def main():return render_template("index.html", sayı=5)

if [B]name[/B] == "[B]main[/B]":app.run(debug=True)

HTML:

HTML:
<!DOCTYPE html>

<html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Arge Flask App</title></head><body>    {% if sayı %}        <p>{{ sayı }}</p>    {% endif %}</body></html>

Using ELSE

Python:

Python:
from flask import Flask, render_template

app = Flask([B]name[/B])

@app.route("/")def main():return render_template("index.html", deneme="Naber")

app.run(debug=True)

HTML:

HTML:
<!DOCTYPE html>

<html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Arge Flask App</title></head><body>    {% if sayı %}        <h1>{{ sayı }}</h1>    {% else %}        <p>Bişey Olmadı</p>    {% endif %}</body></html>

Using ENDIF

Python:

Python:
from flask import Flask, render_template

app = Flask([B]name[/B])

@app.route("/")def main():return render_template("index.html", sayı=5)

app.run(debug=True)

HTML:

HTML:
<!DOCTYPE html>

<html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Arge Flask App</title></head><body>    {% if sayı %}        <p>{{ sayı }}</p>    {% endif %}    <p>İşlem Başarı İle Tamamlandı</p></body></html>

Sending More Than Just Numbers

Of course, we can send more than just numbers. For example, let's make a request to THT and display the status code.

Python:

Python:
from flask import Flask, render_templateimport requests

app = Flask([B]name[/B])

r = requests.get(url="[URL]https://turkhackteam.org/[/URL]")

@app.route("/")def main():return render_template("index.html", status=r.status_code)

app.run(debug=True)

HTML:

HTML:
<!DOCTYPE html>

<html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Arge Flask App</title></head><body>    {% if status %}        <h1>{{ status }}</h1>    {% endif %}</body></html>

Example For Loop

Python:

Python:
from flask import Flask, render_template

app = Flask([B]name[/B])

numaralar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

@app.route("/")def main():return render_template('index.html', sayılar=numaralar)

if [B]name[/B] == "[B]main[/B]":app.run(debug=True)

HTML:

HTML:
<!DOCTYPE html>

<html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Arge Flask App</title></head><body>    {% for donguler in sayılar %}        <p>{{ donguler }}</p>    {% endfor %}</body></html>

That's it for now. In the coming days, I will update the topic by adding database operations, sending data, API creation, and more.

p0qbke2.png
 
It's a nice article, but why are the variable names in Turkish?
 
It's a nice article, but why are the variable names in Turkish?
First of all, thank you for your comment

I translated the topic from Turkish to English, I did not think of making the variable names in English, I will edit it with the topic at a suitable time.
 
p0qbke2.png


Hello everyone, I am Suppressor. Today, I will introduce you to Flask, a micro web framework of Python.

umBqNLP.png


Flask is a simple and lightweight micro web framework used for web development and web applications under the Python programming language. The reason it's called a "micro" web framework is due to its minimal and lightweight structure. Flask provides developers with only the essential tools and can be extended with various libraries when more complex features are needed.

How-to-Create-an-API-Using-The-Flask-Framework-1024x576.png

Flask URL Structure and Routing

Looking at the basic structure and routing of Flask, in the simplest explanation, a request is sent from our computer to our application, and the response to the request is displayed in our browser. When we start a Flask application, it also sets up a server at a local address and we continue our operations from there. Flask automatically determines this address and shows it to us when we start the application.



request-response.jpeg


Routing and Syntax

Syntax:
  • Task: app.route
  • Define Function: def route():
  • Task: return "Hello"
Generally, the syntax is like this:

Python:
from flask import Flask

app = Flask([B]name[/B])

@app.route("/")def route():return "Hello"

if [B]name[/B] == "[B]main[/B]":app.run()

Adding the Flask library to the program and creating a Flask object:

Python:
from flask import Flask

app = Flask([B]name[/B])

Next, we tell Flask which function to run when a certain event occurs using the "route" decorator (decorators are special functions in Python):

Python:
@app.route("/")def route():return "Hello"

At this point, when we go to the root directory, meaning the main URL, we will get a response like "Hello".

Another example is from the /admin directory.

Templates

Templates are structures that exist to interpret languages like HTML, CSS, JS in your browser and display them to the user. As you saw above, we could only place string expressions on the screen. However, using templates, we can have our HTML, CSS, and JavaScript codes interpreted by the browser. Before moving on to the coding phase, we need to create a folder named "templates" in the directory where our Flask application is located. By default, Flask pulls the templates it will interpret from this folder. Then, I create a file named "index.html" inside it. Additionally, you need to include render_template in the library part. You can see it in the code below.

Python:
from flask import Flask, render_template

app = Flask([B]name[/B])

@app.route("/template")def index():return render_template('index.html')

if [B]name[/B] == "[B]main[/B]":app.run(debug=True)

If we want to show an HTML file to the user, we use the render_template() function and write the name of the HTML file we want from the "templates" folder.

Example HTML Code:

HTML:
<!DOCTYPE html>

<html lang="tr"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Arge Team</title>    <script src="https://cdn.tailwindcss.com"></script></head><body><style>    body {        background-color: black;        text-align: center;        font-style: italic;    }    h6 {        color: rgb(220 38 38);    }    p {        color: rgb(132 204 22);    }</style>    <p>Flask</p>    <br>    <h6>Template</h6></body></html>

Sending Data from Flask Application to HTML File

Jinja Syntax

Conditional Statements and Loops

For loops, conditional statements, etc.:

For showing variables:

We learned above how to display the index file to the user. But what if we need to send data from a Flask application we wrote to the user? Let's first look at how to do this.

Again, write the codes I wrote above and similarly write render_template('index.html'). But this time, there's a difference: you can write any name you want, but you need to give one parameter. The name doesn't matter; I gave the parameter name "sayı".

You can define this in the upper lines or directly here:

ctf0sk9.png


Python:
return render_template("index.html", sayı=15)

On the HTML side, you need to specify this variable name inside {{ parameter_name }}.

Examples

Control if a number exists and display it in HTML:

Python:
from flask import Flask, render_template

app = Flask([B]name[/B])

@app.route("/")def main():return render_template("index.html", sayı=5)

if [B]name[/B] == "[B]main[/B]":app.run(debug=True)

HTML:

HTML:
<!DOCTYPE html>

<html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Arge Flask App</title></head><body>    {% if sayı %}        <p>{{ sayı }}</p>    {% endif %}</body></html>

Using ELSE

Python:

Python:
from flask import Flask, render_template

app = Flask([B]name[/B])

@app.route("/")def main():return render_template("index.html", deneme="Naber")

app.run(debug=True)

HTML:

HTML:
<!DOCTYPE html>

<html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Arge Flask App</title></head><body>    {% if sayı %}        <h1>{{ sayı }}</h1>    {% else %}        <p>Bişey Olmadı</p>    {% endif %}</body></html>

Using ENDIF

Python:

Python:
from flask import Flask, render_template

app = Flask([B]name[/B])

@app.route("/")def main():return render_template("index.html", sayı=5)

app.run(debug=True)

HTML:

HTML:
<!DOCTYPE html>

<html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Arge Flask App</title></head><body>    {% if sayı %}        <p>{{ sayı }}</p>    {% endif %}    <p>İşlem Başarı İle Tamamlandı</p></body></html>

Sending More Than Just Numbers

Of course, we can send more than just numbers. For example, let's make a request to THT and display the status code.

Python:

Python:
from flask import Flask, render_templateimport requests

app = Flask([B]name[/B])

r = requests.get(url="[URL]https://turkhackteam.org/[/URL]")

@app.route("/")def main():return render_template("index.html", status=r.status_code)

app.run(debug=True)

HTML:

HTML:
<!DOCTYPE html>

<html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Arge Flask App</title></head><body>    {% if status %}        <h1>{{ status }}</h1>    {% endif %}</body></html>

Example For Loop

Python:

Python:
from flask import Flask, render_template

app = Flask([B]name[/B])

numaralar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

@app.route("/")def main():return render_template('index.html', sayılar=numaralar)

if [B]name[/B] == "[B]main[/B]":app.run(debug=True)

HTML:

HTML:
<!DOCTYPE html>

<html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Arge Flask App</title></head><body>    {% for donguler in sayılar %}        <p>{{ donguler }}</p>    {% endfor %}</body></html>

That's it for now. In the coming days, I will update the topic by adding database operations, sending data, API creation, and more.

p0qbke2.png
The topic is very nice, I wish you a good day.
 
Geri
Üst

Turkhackteam.org internet sitesi 5651 sayılı kanun’un 2. maddesinin 1. fıkrasının m) bendi ile aynı kanunun 5. maddesi kapsamında "Yer Sağlayıcı" konumundadır. İçerikler ön onay olmaksızın tamamen kullanıcılar tarafından oluşturulmaktadır. Turkhackteam.org; Yer sağlayıcı olarak, kullanıcılar tarafından oluşturulan içeriği ya da hukuka aykırı paylaşımı kontrol etmekle ya da araştırmakla yükümlü değildir. Türkhackteam saldırı timleri Türk sitelerine hiçbir zararlı faaliyette bulunmaz. Türkhackteam üyelerinin yaptığı bireysel hack faaliyetlerinden Türkhackteam sorumlu değildir. Sitelerinize Türkhackteam ismi kullanılarak hack faaliyetinde bulunulursa, site-sunucu erişim loglarından bu faaliyeti gerçekleştiren ip adresini tespit edip diğer kanıtlarla birlikte savcılığa suç duyurusunda bulununuz.