mirror of
https://gitea.com/mcereda/oam.git
synced 2026-02-08 21:34:25 +00:00
6.0 KiB
6.0 KiB
Python
Table of contents
- TL;DR
- Dictionaries
- F-strings
- Logging
- Web servers
- Execute commands on the host
- Concurrent execution
- Further readings
- Sources
TL;DR
# Declare a dictionary.
{'spam': 2, 'ham': 1, 'eggs': 3}
dict(spam=2,ham=1,eggs=3)
dict([('spam',2),('ham',1),('eggs',3)])
# String formatting with f-strings.
f"Hello, {name}. You are {age}."
F"{name.lower()} is funny."
# Make elements in a list unique.
# Keep the resulting list mutable.
unique_elements = list(set(redundant_elements))
Dictionaries
# Declare a dictionary.
d = {'spam': 2, 'ham': 1, 'eggs': 3}
d = dict(spam=2,ham=1,eggs=3)
d = dict([('spam',2),('ham',1),('eggs',3)])
d = {x: x for x in range(5)}
d = {c.lower(): c + '!' for c in ['SPAM','EGGS','HAM']}
d = dict.fromkeys('abc',0)
# Change an element.
d['ham'] = ['grill', 'bake', 'fry']
# Add a new element.
d['brunch'] = 'bacon'
# Delete an element.
del d['eggs']
d.pop('eggs')
# List values and/or keys.
d.values()
d.keys()
d.items()
# Print the elements and their values.
for k,v in d.items(): print(k,v)
# Merge dictionaries.
d1 = {'spam': 2, 'ham': 1, 'eggs': 3}
d2 = {'toast': 4, 'muffin': 5, 'eggs': 7}
d1.update(d2)
# Copy dictionaries.
d1 = {'spam': 2, 'ham': 1, 'eggs': 3}
d2 = d1.copy()
F-strings
f"Hello, {name}. You are {age}."
F"{name.lower()} is funny."
Logging
Very basic logger:
import logging
logging.basicConfig(level=logging.WARNING)
logging.critical("CRITICAL level message")
logging.exception("ERROR level message")
logging.error("ERROR level message")
logging.warning("WARNING level message")
logging.info("INFO level message")
logging.debug("DEBUG level message")
logging.log(level, "{level} level message")
See logging howto and logging library for more information.
Web servers
Flask
request.argsgets query argumentsrequest.formgets POST arguments
from flask import request, jsonify
@app.route('/get/questions/', methods=['GET', 'POST','DELETE', 'PATCH'])
def question():
if request.method == 'GET':
start = request.args.get('start', default=0, type=int)
limit_url = request.args.get('limit', default=20, type=int)
data = [doc for doc in questions]
return jsonify(
isError = False,
message = "Success",
statusCode = 200,
data= data
), 200
if request.method == 'POST':
question = request.form.get('question')
topics = request.form.get('topics')
return jsonify(
isError = True,
message = "Conflict",
statusCode = 409,
data = data
), 409
WSGI server
You can use waitress:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "<h1>Hello!</h1>"
if __name__ == "__main__":
from waitress import serve
serve(app, host="0.0.0.0", port=8080)
pip install flask waitress
python hello.py
Execute commands on the host
Very basic execution:
import subprocess
subprocess.call(command)
See subprocess library for more information.
Concurrent execution
Very basic multi-threaded operations:
from concurrent.futures import ThreadPoolExecutor
from os import cpu_count
with ThreadPoolExecutor(max_workers=cpu_count()) as executor:
for element in elements:
logging.debug(f"submitting thread for {element}")
executor.submit(function_name, function_arg_1, function_arg_n)
See concurrent execution for more information.
Further readings
- Dictionaries
- PIP
- How To Update All Python Packages
- invl/pip-autoremove
- Data types
- F-strings
- How to filter list elements in Python
- Logging howto
- Flask at first run: do not use the development server in a production environment
- Flask example with POST
- Multi-value query parameters with Flask
- *args and **kwargs in Python
- An intro to threading in Python
- ThreadPoolExecutor in Python: the complete guide
- Concurrent execution