Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
qaqaqaqaowh committed Apr 8, 2020
0 parents commit 5519f00
Show file tree
Hide file tree
Showing 33 changed files with 6,106 additions and 0 deletions.
17 changes: 17 additions & 0 deletions LISCENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
MIT License
Copyright (c) 2018 YOUR NAME
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A package aimed to automate creation of flask app template.
2 changes: 2 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[metadata]
description-file = README.md
34 changes: 34 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from setuptools import setup, find_packages
setup(
name = 'ftg',
packages = find_packages(),
version = '0.5',
license='MIT',
description = 'A generator for a flask app template',
author = 'Nicholas Ong Wei Harn',
author_email = 'nicholasowh@hotmail.com',
url = 'https://github.com/qaqaqaqaowh/ftg',
download_url = 'https://github.com/qaqaqaqaowh/ftg/archive/0.5.tar.gz',
keywords = ['flask', 'template', 'generate'],
install_requires=[
'flask',
'peewee',
'peewee-db-evolve',
'python-dotenv',
'psycopg2-binary',
'Flask-Assets',
'cssmin',
'jsmin',
'Flask-Cors'
],
entry_points = {
'console_scripts': ['ftg=src.__main__:main'],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.7'
],
)
Empty file added src/__init__.py
Empty file.
17 changes: 17 additions & 0 deletions src/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import argparse
from .templates import gen_template

def main():
parser = argparse.ArgumentParser(prog='flask-template', description="A flask app template generator.")

parser.add_argument("command", choices=["new"], help="Commands to run, allowed values are: new => For template generation")

parser.add_argument("name", help="Name for the resource generation")

args = parser.parse_args()

if args.command == "new":
gen_template(args.name)

if __name__ == "__main__":
main()
15 changes: 15 additions & 0 deletions src/files/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from .readme import readme
from .gitignore import gitignore
from .app import app
from .env import env
from .start import start
from .templates_layout import templates_layout

__all__ = [
"readme",
"gitignore",
"app",
"env",
"start",
"templates_layout"
]
32 changes: 32 additions & 0 deletions src/files/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from textwrap import dedent

def app(name):
return dedent(f"""\
import os
import config
from flask import Flask
from models.base_model import db
web_dir = os.path.join(os.path.dirname(
os.path.abspath(__file__)), '{name}_web')
app = Flask('{name}', root_path=web_dir)
if os.getenv('FLASK_ENV') == 'production':
app.config.from_object("config.ProductionConfig")
else:
app.config.from_object("config.DevelopmentConfig")
@app.before_request
def before_request():
db.connect()
@app.teardown_request
def _db_close(exc):
if not db.is_closed():
print(db)
print(db.close())
return exc
""")
8 changes: 8 additions & 0 deletions src/files/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from textwrap import dedent

def env(name):
return dedent(f"""\
FLASK_ENV=development
FLASK_APP=start
DATABASE_URL=postgres://localhost:5432/{name}_dev
""")
11 changes: 11 additions & 0 deletions src/files/gitignore.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from textwrap import dedent

def gitignore(name):
return dedent(f"""\
.vscode
*.DS_Store
*__pycache__
*.env
{name}_web/static/.webassets-cache
{name}_web/static/gen
""")
163 changes: 163 additions & 0 deletions src/files/readme.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
from textwrap import dedent

def readme(name):
return dedent(f"""\
# Flask {name} Template
version 0.0.1 (alpha)
## Development
**Make a fork before cloning**
**Install dependencies**
- Python 3.7.2 was tested
- Postgresql 10.3 was tested
1. Delete `peewee-db-evolve==3.7.0` from `requirements.txt` during the first installation.
Because of how `peewee-db-evolve` created it's build process, we would first need to delete it.
1. Run:
```
pip install -r requirements.txt
```
1. Now add `peewee-db-evolve==3.7.0` back into `requirements.txt`
1. Run again:
```
pip install -r requirements.txt
```
If you're having trouble installing dependencies
- Remove `certifi==2018.11.29` from requirements.txt
If you're having trouble starting flask
- Restart your terminal as well and reactivate conda source
**Create a `.env` file at the root of the directory**
This project uses `python-dotenv`. When running commands using `flask`, environment variables from `.env` are automatically loaded.
When executing `python` scripts directly e.g. `python start.py`, environment variables are not loaded and will not work except `python migrate.py` _(read the script - `migrate.py` to know why it would load the environment variables `.env`)_
Minimum environment variables that needs to be set
```
FLASK_APP='start' # based on the name of our entry point script
FLASK_ENV='development' # use this in development, otherwise 'production' or 'test'
DATABASE_URL="postgres://localhost:5432/{name}_dev"
SECRET_KEY= #generate your own key
```
Use `os.urandom(32)` to generate a random secret key and paste that in `.env`. It's important to keep this `SECRET_KEY` private.
Since this app uses Pooled Connections, you may also want to set:
```
DB_TIMEOUT=300 # 5 minutes
DB_POOL=5
```
_(see `database.py`)_
**Create a Database**
- this application is configured to use Postgresql
```
createdb {name}_dev
```
_\*if you name your database something else, tweak the settings in `.env`_
**Ignoring Files from Git**
Before git commiting, remember to ignore key files. Here's an example of `.gitignore`
```
.vscode
*.DS_Store
*__pycache__
*.env
```
---
## Database Migrations
```
python migrate.py
```
\*_this template is configured to use Peewee's PooledConnection, however, migrations using Peewee-DB-Evolve doesn't work well. A hack was used to not use PooledConnection when running migration. Pending investigation. There are no known side effects to run this template in production._
## Starting Server
```
flask run
```
## Starting Shell
```
flask shell
```
---
## Deploying to Production
- ensure environment variables are configured appropriately
- migrations will not run in interactive mode when FLASK_ENV is set to 'production'
- It's important to set your own `SECRET_KEY` environment variable and keep that private.
---
## Architecture
This template separates out API and Web to separate packages. Both API and Web are configured to use Flask's Blueprints.
All new models should go into it's own file/script within the models directory.
The entry point for a Flask server to start is located at `start.py`
---
## Dependencies
This template was created against `Python 3.7`. Should work with newer versions of Python. Not tested with older versions.
`Peewee` is used as ORM along with a database migration library `peewee-db-evolve`.
This template also comes packaged with Bootstrap 4.1.3 and it's dependencies (jQuery).
A copy of requirements.txt is included in the repository.
```
autopep8==1.4.3
certifi==2018.11.29
Click==7.0
colorama==0.4.1
Flask==1.0.2
Flask-Cors==3.0.7
itsdangerous==1.1.0
Jinja2==2.10
MarkupSafe==1.1.0
peewee==3.8.2
peewee-db-evolve==3.7.0
psycopg2-binary==2.7.7
pycodestyle==2.5.0
python-dotenv==0.10.1
six==1.12.0
Werkzeug==0.14.1
```
Remove `certifi==2018.11.29` if you're having trouble installing dependencies.
---
This repository belongs to [NEXT Academy](https://www.nextacademy.com/?utm_source=github&utm_medium=student-challenge&utm_campaign=flask-nextagram) and is a part of NEXT Academy's coding bootcamps. You may find more information about our bootcamp at https://www.nextacademy.com
If you are already a student, you may find the challenge description at https://code.nextacademy.com/lessons/day-1--starting-template/479
""")
11 changes: 11 additions & 0 deletions src/files/start.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from textwrap import dedent

def start(name):
return dedent(f"""\
from app import app
import {name}_api
import {name}_web
if __name__ == '__main__':
app.run()
""")
4 changes: 4 additions & 0 deletions src/files/static/api/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from app import app
from flask_cors import CORS

cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
31 changes: 31 additions & 0 deletions src/files/static/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import os


class Config(object):
DEBUG = False
TESTING = False
CSRF_ENABLED = True
SECRET_KEY = os.environ.get(
'SECRET_KEY') or os.urandom(32)


class ProductionConfig(Config):
DEBUG = False
ASSETS_DEBUG = False


class StagingConfig(Config):
DEVELOPMENT = False
DEBUG = False
ASSETS_DEBUG = False


class DevelopmentConfig(Config):
DEVELOPMENT = True
DEBUG = True
ASSETS_DEBUG = False

class TestingConfig(Config):
TESTING = True
DEBUG = True
ASSETS_DEBUG = True
Loading

0 comments on commit 5519f00

Please sign in to comment.