from pathlib import Path
# Read file content
def read_file():
test_file = "example/you_test_file.txt"
contents = Path(test_file).read_text()
print (contents) # print file content
#debug(contents) # use can also use my custom debug method to see log in file
# To write message to file for debugging
def debug(message="", type="w+"):
filePath = "test/debug.txt" # don't forgot to create a empty file
with open(filePath, type) as f:
f.write(str(message) + "\n\n")
f.close()
Wednesday, 2 November 2022
Python - To read file content & write into a file
Thursday, 19 May 2022
Simple bash stements to set values covering following two scenarios:
1. Set username/password variable if value passed on running the file
2. Or (step 1 doesn't pass values), set them on prompt arguments
Create a login.sh file using the below content:
#!/bin/sh
# set -o errexit -o nounset -o xtrace
echo "Initialising Username/Password: "
if test "${1+x}"; then # Set values from inline statement
username=$1
password=$2
else # Otherwise, set values from arguments
read -p 'Username: ' username
read -sp 'Password: ' password
fi
echo 'Username: ' $username '| Password: ' $password
1. First scenario, passing the values whilst running the file
$ sh login.sh nepal.user Pokhara123 Username: nepal.user | Password: Pokhara1232. Second scenario, passing the values on prompt arguments
$ sh login.sh $ sh login.sh Initialising Username/Password: Username: nepal.user Password: Pokhara123 Username: nepal.user | Password: Pokhara123
Wednesday, 27 April 2022
Build Dynamic Marshal_With in Flask (Python) based on conditions
To create a dynamic marshalling based on condition or parameter type, please follow the instruction below:
# Constants
MARSHELL_WITH_SCHEMAS = {
"condition_1": Condition1Schema,
"condition_2": Condition2Schema,
}
# To build dynamic marshalling based on report type
def selective_marshal_with():
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
condition_type = kwargs.get("condition_type", None)
# Get marshalled with dynamic schema by condition type
marshal_with_func = marshal_with(MARSHELL_WITH_SCHEMAS.get(condition_type, None))(func)
return marshal_with_func(*args, **kwargs)
return wrapper
return decorator
# Actual class to connect view to URL
class MyViewClass(MethodResource, Resource):
@doc(description="My View API", tags=["My View List"])
@use_kwargs(MyQueryParams, location="query")
@selective_marshal_with()
@standard_api("My View List")
def get(self, **kwargs):
# you get code here....
The MyQueryParams can/should be in seperate schema file for e.g. rest/db/schema/my_view_schema.py
class MyQueryParams(Schema):
"""Query parameters for View List API."""
condition_type = fields.Str(attribute="condition_type", required=True)
Hope it helps!
Subscribe to:
Comments (Atom)