geomon/gschliefgraben_glasfaser/main.py
2022-02-23 16:46:47 +01:00

91 lines
2.8 KiB
Python

'''
Tutorial link: https://realpython.com/flask-connexion-rest-api-part-2/
https://github.com/realpython/materials/blob/master/flask-connexion-rest-part-2/version_1/people.py
Sqlalchemy version: 1.2.15
Python version: 3.7
'''
import os
# import sys, inspect
# currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
# parentdir = os.path.dirname(currentdir)
# sys.path.insert(0, parentdir)
from sqlalchemy.orm import session
from models import ObservationSchema, Person, PersonSchema, Observation
from db.pg_models import create_pg_session
#from models import Person, PersonSchema
# response = requests.get('https://api.com/')
# print(response) # shows the response's HTTP status code
# print(response.json()) # shows the response's JSON response body, if it has one
# print(response.content) # get the data content of the response
def main():
''' main method '''
db_user = os.environ.get("POSTGIS_DBUSER")
print(db_user)
pg_session: session = create_pg_session()
# pg_person: Person = pg_session.query(Person).first()
observation: Observation = pg_session.query(Observation).first()
print (observation)
# serialize db data to json
# person_schema = PersonSchema()
# dump_data = person_schema.dump(pg_person)
# print(dump_data)
# serialize db data to json
observation_schema = ObservationSchema()
dump_data = observation_schema.dump(observation)
print(dump_data)
# # deserialize
# load_data: Person = person_schema.load(dump_data)
# print(load_data)
# create(dump_data)
def create(person_json: PersonSchema):
"""
This function creates a new person in the people structure
based on the passed-in person data
:param person: person to create in people structure
:return: 201 on success, 406 on person exists
"""
login = person_json.get('login')
#lname = person.get('lname')
db_session = create_pg_session()
# existing_person = Person.query \
# .filter(Person.login == login) \
# .one_or_none()
existing_person: bool = ( \
db_session.query(Person) \
.filter(Person.login == login)
.one_or_none()
)
# Can we insert this person?
if existing_person is None:
# Create a person instance using the schema and the passed in person
schema = PersonSchema()
# deserialize to object
new_person: Person = schema.load(person_json)
# Add the person to the database
db_session.add(new_person)
db_session.commit()
# Serialize and return the newly created person in the response
data = schema.dump(new_person)
return data, 201
# Otherwise, nope, person exists already
else:
print(409, f'Person {login} exists already')
if __name__ == "__main__":
main()