From 890c7716b3c8ebcf147c8ee4b030c219bd0fa4fe Mon Sep 17 00:00:00 2001 From: Sommerschein <> Date: Tue, 21 Mar 2023 01:34:07 +0000 Subject: [PATCH] Initial commit --- .gitignore | 154 ++++++++++++++++++++++++++++++++++++++++++++++++++ LICENSE | 121 +++++++++++++++++++++++++++++++++++++++ README.md | 3 + __init__.py | 0 app.py | 13 +++++ config.py | 40 +++++++++++++ models.py | 10 ++++ rebuild_db.py | 18 ++++++ schemes.py | 25 ++++++++ services.py | 46 +++++++++++++++ wsgi.py | 5 ++ 11 files changed, 435 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 __init__.py create mode 100644 app.py create mode 100644 config.py create mode 100644 models.py create mode 100644 rebuild_db.py create mode 100644 schemes.py create mode 100644 services.py create mode 100644 wsgi.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..55be276 --- /dev/null +++ b/.gitignore @@ -0,0 +1,154 @@ +# ---> Python +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintainted in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/LICENSE @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/README.md b/README.md new file mode 100644 index 0000000..81ddec8 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# Backend-Boilerplate + +Ein Kleines Boilerplate um Flask-Backends zu erstellen \ No newline at end of file diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app.py b/app.py new file mode 100644 index 0000000..6104bec --- /dev/null +++ b/app.py @@ -0,0 +1,13 @@ +from services import (UserService, UserListService) +from config import app, api, docs, CORS + +#*______________ Service Registration ______________ +api.add_resource(UserService, '/api/user/') +docs.register(UserService) +api.add_resource(UserListService, '/api/list/user') +docs.register(UserListService) +#*______________ Application Creation ______________ +if __name__ == '__main__': + app.run(debug=True) + + diff --git a/config.py b/config.py new file mode 100644 index 0000000..4d75670 --- /dev/null +++ b/config.py @@ -0,0 +1,40 @@ +from flask import Flask +from flask_restful import Api +from apispec import APISpec +from apispec.ext.marshmallow import MarshmallowPlugin +from flask_apispec.extension import FlaskApiSpec +from flask_marshmallow import Marshmallow +from flask_sqlalchemy import SQLAlchemy +from flask_cors import CORS +#!______________ App Setup _____________ _ +app = Flask(__name__, static_url_path='/static') +api_v1_cors_config = { + "origins": ["http://localhost:5000"] +} + +#!______________ CORS Setup _____________ _ +CORS(app, resources={"/api/*": api_v1_cors_config}) + +#!______________ DB Setup ______________ +app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///markdown.db' +app.config['SECRET_KEY'] = 'InputSecretKeyHere' +db = SQLAlchemy(app) + +#!______________ Marshmallow Setup ______________ +ma = Marshmallow(app) + +#!______________ API & Swagger Setup ______________ +api = Api(app) +app.config.update({ + 'APISPEC_SPEC': APISpec( + title='Markdown Presenter', + version='v0.0.1', + plugins=[MarshmallowPlugin()], + openapi_version='2.0.0' + ), + 'APISPEC_SWAGGER_URL': '/swagger/', + 'APISPEC_SWAGGER_UI_URL': '/swagger-ui/' +}) + +#!______________ Docs Setup ______________ +docs = FlaskApiSpec(app) \ No newline at end of file diff --git a/models.py b/models.py new file mode 100644 index 0000000..5ac9c7b --- /dev/null +++ b/models.py @@ -0,0 +1,10 @@ +from config import db + +#!______________ DB Models ______________ +class User(db.Model): + __tablename__ = "User" + id = db.Column(db.Integer, primary_key=True) + name = db.Column(db.String(50)) + image = db.Column(db.String()) + description = db.Column(db.String()) + diff --git a/rebuild_db.py b/rebuild_db.py new file mode 100644 index 0000000..2c56232 --- /dev/null +++ b/rebuild_db.py @@ -0,0 +1,18 @@ +import os +from config import db +from termcolor import colored +from config import app + +def RebuildDatabase(): + if os.path.exists('acceth.db'): + print(colored('Removing existing DB', 'blue')) + os.remove('acceth.db') + + with app.app_context(): + db.create_all() + db.session.commit() + + print(colored('New DB created.', 'green')) + +if __name__ == '__main__': + RebuildDatabase() \ No newline at end of file diff --git a/schemes.py b/schemes.py new file mode 100644 index 0000000..7f180fd --- /dev/null +++ b/schemes.py @@ -0,0 +1,25 @@ +from marshmallow_sqlalchemy import SQLAlchemyAutoSchema +from config import db +from models import User +from marshmallow import fields + +#*______________ Base Schema ______________ +class BaseScheme(SQLAlchemyAutoSchema): + def __str__(self): + return str(self.__class__) + ": " + str(self.__dict__) + class Meta: + ordered = True + sqla_session = db.session + include_fk = True + load_instance = True + +#*______________ User Schemes ______________ +class UserSchema(BaseScheme): + class Meta(BaseScheme.Meta): + model = User + id = fields.Int() + name = fields.Str() +class UserInsertSchema(UserSchema): + user_id = fields.Int() +class UserResponseSchema(UserSchema): + name = fields.Str() \ No newline at end of file diff --git a/services.py b/services.py new file mode 100644 index 0000000..70568ed --- /dev/null +++ b/services.py @@ -0,0 +1,46 @@ +from flask_apispec import marshal_with, doc, use_kwargs +from flask_apispec.views import MethodResource +from flask_restful import Resource +from schemes import (UserSchema, UserResponseSchema) +from config import db +from models import User + +#!______________ User ______________ +class UserService(MethodResource, Resource): + @doc(description='Get User by User_id', tags=['User']) + @marshal_with(UserResponseSchema) + def get(self, user_id): + quser = db.session.query(User).get(user_id) + return UserSchema().dump(quser) + + @doc(description='Add new User', tags=['User']) + @use_kwargs(UserSchema, location=('json')) + @marshal_with(UserResponseSchema()) + def post(self, user, user_id): + db.session.add(user) + db.session.commit() + return UserSchema().dump(user) + + @doc(description='Update User with PUT', tags=['User']) + @use_kwargs(UserSchema, location=('json')) + @marshal_with(UserResponseSchema()) + def put(self, user, user_id): + db.session.add(user) + db.session.commit() + return UserSchema().dump(user) + + @doc(description='Delete existing User', tags=['User']) + @use_kwargs(UserSchema, location=('json')) + @marshal_with(UserResponseSchema()) + def delete(self, user, user_id): + user = db.session.query(User).get(user_id) + db.session.delete(user) + db.session.commit() + return UserSchema().dump(user) + +class UserListService(MethodResource, Resource): + @doc(description='Get a List of all User', tags=['List']) + @marshal_with(UserResponseSchema(many=True)) + def get(self): + users = db.session.query(User).all() + return UserSchema(many=True).dump(users) \ No newline at end of file diff --git a/wsgi.py b/wsgi.py new file mode 100644 index 0000000..0ad1c54 --- /dev/null +++ b/wsgi.py @@ -0,0 +1,5 @@ +from config import app + +if __name__ == "__main__": + app.run() +