/ Python

Python's Flask

Flask basic stuff

Below are mostly basic stuff to begin with Flask

Basic example

Here's a very basic example, with GET, POST, cookie...

from flask import Flask, request, make_response, render_template
import os

app = Flask(__name__)
count = 0

@app.route('/')
def hello_world():
    return 'Death or /tchitchi ?'

@app.route('/tchitchi')
def tchitchi():
    global count
    answer = "tchi " * count
    count += 1
    return answer

@app.route('/victim/<string:victim>')
def victim(name):    
    return "tchi tchi " + name

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return "login POST parameters : " + ', '.join(request.form)
    else:
        return "login GET"

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():    
    answer = 'upload KO'
    if request.method == 'POST':
        f = request.files['the_file']
        f.save('upload/file.txt')
        answer = "Upload OK"
        os.remove('upload/file.txt')
    elif request.method == 'GET':
        answer = 'upload GET'            
    return answer


@app.route('/cookie/', methods=['GET', 'POST'])
@app.route('/cookie/<string:contenu>', methods=['GET', 'POST'])
def cookie(content=None):
    answer = "No cookie"
    if request.method == 'POST':
        resp = make_response(render_template('sample_template.html', payload=content))
        resp.set_cookie('content', content)
        answer = resp
    elif request.method == 'GET':
        answer = "Cookie content = " + request.cookies.get('content')
    return answer

if __name__ == '__main__':
    app.run()

(Jinja) template

Same as Ansible's, for example sample_template.html as called above

<!DOCTYPE html>
<html>
    <body>
        <h1>Sample template</h1>
        <p>This is a sample html template to play with Flask</p>
        <p>here is the payload var : {{ payload }}"</p>
    </body>
</html>

(PyCharm's) http requests

This can be saved as .http files then PyCharms can call them

A simple GET

GET http://localhost:5000/victim/marc
Accept: */*
Cache-Control: no-cache

###

A POST request for login form

### Send a form with the text and file fields
POST http://localhost:5000/login
Content-Type: multipart/form-data; boundary=WebAppBoundary

--WebAppBoundary
Content-Disposition: form-data; name="login"
Content-Type: text/plain

marc
--WebAppBoundary
Content-Disposition: form-data; name="password"
Content-Type: text/plain

stupidDefaultPasswordWithNoMeaning
--WebAppBoundary--

###

A POST request with a sample txt file for upload form

### Send a form with the text and file fields
POST http://localhost:5000/upload
# POST https://httpbin.org/post
Content-Type: multipart/form-data; boundary=WebAppBoundary

--WebAppBoundary
Content-Disposition: form-data; name="the_file"; filename="sample_file.txt"
Content-Type: text/plain

< ./sample_file.txt
--WebAppBoundary--

###
Python's Flask
Share this