Code Monkey home page Code Monkey logo

flask-empty's Introduction

Flask Empty

version 0.6.5

Flask-Empty is a simple flask boilerplate for fast prototyping. Just use cookiecutter and create a new project in no time.

# if cookiecutter is not installed
pip3 install cookiecutter

# using cookiecutter // linux/Mac
cookiecutter https://github.com/italomaia/flask-empty

# answer the prompt and you're done!

Getting Started

You're advised to use venv from here on. In your project folder, create and enable it like this:

python3 -m venv venv
. venv/bin/activate  # [.csh|.fish]

# install required packages
pip3 install -r requirements.txt

# loads env variables and runs the project in development mode
make run-dev

Getting Started With Docker

Given you have up-to-date docker installed in your machine, all you need to do is:

# build container image
docker build . -t my-project-name
# run container in development mode
docker run --rm -p 5000:5000 my-project-name

Environment Variables

For flask to run correctly, some environment variables need to be set. The ones needed by your project can be seen in the Dockerfile or Makefile files. For a list of all other optional environment variables, check this link. When using docker, you can easely set them inline before each run. When using docker-compose, set them in the yaml configuration file for each environment.

Important files to be aware of

/extensions.py all extension instances that need initialization should be available here, so Empty can see and initialize them for you. If instantiated somewhere else, just import them here and you should be fine.

/config.py has pre-set configuration classes for you to meddle with. They're are all self explanatory and commented.

/main.py instantiates your project's main class. Override it to quickly add custom extension setups, simple views, context processors, etc. It already has some sensitive defaults for most use cases. See https://github.com/italomaia/empty for the available options.

<project>/<project>.ini is the configuration file used with uwsgi. Use it like this:

uwsgi --ini your_project.ini

commands.py adds few very useful commandline commands (...) to help your development productivity. You can also add your own. Check available commands by running FLASK_ENV=development FLASK_CONFIG_DEFAULT=Dev flask in the terminal.

Heroku

Empty comes with a pre-configured procfile and heroku() wrapper for app_factory. No setup required.

Other topics

Templates

There are some error templates bundled with flask-empty by default. All empty right now. Just fill them up for your project.

Macros

You can use the jinja2 macros available in templates/macros to easily integrate your jinja2 templates with flask extensions like wtforms and common tasks like showing flash messages.

Available macros, formhelpers and flashing are very useful.

Blueprints

You can create blueprints easily with make new-app. The will live, by default at apps folder. Remember to configure your blueprints in config.py so that they can be properly loaded.

Json Friendly

Variables true, false and null are now supported as aliases for True, False and None. This way, valid json can be copy-pasted directly into your code and will be interpreted as valid python. Ex: data = {"x": true, "y": false, "z": null}

Supported Extensions

Flask-SQLAlchemy

While creating your project, Flask-Empty will ask you if you wish to enable SQL support. Confirm if you do so and Flask-SQLAlchemy will be made available. See config.py for its default configuration.

_ps: currently, db-create will only create your models if they are imported somewhere in your application.

By somewhere, try the same module where your Blueprint instance is defined.

Flask-Mongoengine

As mongodb is really cool, supporting it is a must. Just say yes at the prompt when asked and Flask-Mongoengine will be setup for you.

Flask-WTF

Flask-WTF is the "the facto" extension for handling forms with Flask. It is simply great, and Flask-Empty supports it! Just say "yes" during project creation and Flask-WTF support will be on.

Flask-Admin

Just create an admin.py file in your blueprint, define your admin models inside and change LOAD_MODULES_EXTENSIONS to also pre-load admin, like this:

Flask-Marshmallow

Gives you, almost for free, model serialization, deserialization and validation. Also quite handy for fast development of rest applications.

Flask-Security

Get user session and permissioning out-of-the-box with this great project.

Examples

The blog example in this project is probably outdated by now, so, just create a new project and mess around to your heart's content for quick learning.

FAQ

Is flask-empty boilerplate compatible with flask 0.x? Cuz' that's what my app uses.

Right now, flask-empty is a very simple project where many good practices and code examples were glued together.

Until recently I was focused in keeping backward compatibility with flask 0.8. Well, that goal is no more.

Flask-empty will be compatible with the latest version of Flask and, by chance, with previous versions. Things will be easier (for me!) this way.

So, which is the oldest version where flask-empty works?

In my last test, version 1.0.

I think flask-empty should have this and that configured by default. Will you add support?

My current goals are:

  • Make flask-empty real easy to start a project with
  • Keep things simple and robust

If your suggestion is simple, VERY useful and has little overhead, I'll probably consider adding it to the project.

If you make the code and send a pull request, then I'll consider it real hard. Now, if your suggestion is rejected or advised in a different approach, don't get sad (you're awesome ;).

I just made a cool example with flask-empty and want to add it to examples.

Pull request it for evaluation ;) Just keep in mind that good examples are short (not really...) and focused in it's showcase.

flask-empty's People

Contributors

ayvazj avatar esaurito avatar gitter-badger avatar italomaia avatar ivopanjos avatar kirillstr avatar monkpit avatar nassty avatar pampersrocker avatar plars avatar royopa avatar wisemuji avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flask-empty's Issues

Any ideas on how to deploy on Google App Engine?

I'm getting this error:

Failed to find attribute 'app' in 'main'.

This is the app.yaml I was using:

runtime: python37

automatic_scaling:
  min_idle_instances: 1

inbound_services:
  - warmup


handlers:

  # This configures Google App Engine to serve the files in the app's static
  # directory.
- url: /static
  static_dir: static

  # This handler routes all requests not caught above to your main app. It is
  # required when static routes are defined, but can be omitted (along with
  # the entire handlers section) when there are no static files defined.
- url: /.*
  script: auto
  secure: always

I tried specifying the entrypoint on the yaml file

entrypoint: gunicorn -b :$PORT wsgi:app

but it didn't work

https://cloud.google.com/appengine/docs/standard/python3/runtime#application_startup

I'm testing locally with:

dev_appserver.py

https://cloud.google.com/appengine/docs/standard/python3/testing-and-deploying-your-app

Implements tests in blueprints

Hi! Great bootstrap project :)

How you handle the tests is interesting, and I think it could go a bit further :

When calling test from the manage.py, it should lookup in the tests folder in the root app, but also in each registered blueprints.

In that way, each blueprint would have it's own set of tests.

I'd like to submit a pull for this kind of idea but I don't know how to loop over blueprints in the test case.

Update/add Flask-Security-Too

For the past 6 months I have been resurrecting Flask-Security - alas requiring my own fork at:
https://github.com/jwag956/flask-security

The original Flask-Security basically has stopped being maintained. I would like to either
ADD Flask-Security-Too as an additional supported extension OR replace Flask-Security.

I am willing to do the PR - just want guidance/approval of the idea.

Heroku integration

Add heroku integration routines. By that I mean procfile and app_factory wrapper.

Old code

I would like to point out that the code provided here, whilst being very fruitful for learning, doesn't conform to the newer version of Flask' s import statements.

Otherwise, this was extremely useful when I was trying to figure out how to separate routes into different files (so that I can group my routes), e.g. social_routes.py and api_routes.py

Thanks.

ModuleNotFoundError: No module named 'flask.ext'

Olá, tentei instalar o seu projeto em minha máquina, para conhecer melhor, mas me deparei com o erro descrito no título.
Segue o meu passo a passo: ativei o virtualenv, logo em seguida, instalei o arquivo requirements.txt que fica na página examples, e, então executei python manage.py create_db.

Mensagem de erro: Traceback (most recent call last): File "manage.py", line 3, in <module> from flask.ext import script ModuleNotFoundError: No module named 'flask.ext'

A seguir, adicionei export FLASK_APP=manage.py e, então, executei flask run.

Mensagem de erro: ImportError: No module named ext

Pesquisei um pouco e encontrei que flask.ext não está em uso:

blueprint already registered

I get this warning that will become an error:

UserWarning: The name 'foobar' is already registered for this blueprint. Use 'name=' to provide a unique name. This will become an error in Flask 2.1.
  self.register_blueprint(blueprint, **kw)

I checked out the source and in main.py app_factory() calls app.add_blueprint_list(). However, flask-security also tries to register all blueprints. Since flask's add_blueprint() method doesn't check wether a blueprint is already registered or not, it is attempted to register the same blueprints twice.

You can not unregister a blueprint:

The downside is that you cannot unregister a blueprint once an application was created without having to destroy the whole application object.

Who should fix this? add_blueprint is a part of flask … should every caller implement their own logic to check if a blueprint was already registered?

Create API example

Right now we have a blog example using sqlalchemy. It would be nice to have a full API example using good practices (OpenAPI, Swagger, Rest).

Communication between apps

Hello,
I recently tried this project (it's really cool), and now I'm using it for a project of myself.
(I would say I have quite a bit of flask knowledge)
But I found a problem I couldn't solve by myself so far: How can you call a function from outer scope (e.g. from another app or an utils folder for general functions)?

As soon as you import something like e.g. utils (outer scope) in views (inner scope) it crashes on startup with multiple exceptions like [app name].app not found and a general flask.cli.NoAppException.

I would like to use this for better code organization and make global functions like is_user_logged_in() (This specifically because I can't use Flask-Security-Too in this project)

What can I do about this?

Thank you for helping me out!

And sorry for the formatting I'm in a hurry for work :(

Edit: I found out I can't even create a util.py file in an app, and the config LOAD_MODULES_EXTENSIONS does nothing even if I add utils there.. am I doing something wrong?

Error message: 'dict object' has no attribute 'create_index'

(flask)    dsc:$ cookiecutter https://github.com/italomaia/flask-empty
Cloning into 'flask-empty'...
remote: Counting objects: 738, done.
remote: Total 738 (delta 0), reused 0 (delta 0), pack-reused 738
Receiving objects: 100% (738/738), 118.09 KiB, done.
Resolving deltas: 100% (363/363), done.
project_name [Your Project Name]: findex-gui
repo_name [findex-gui]: 
version [0.1]: 
create_index_view [yes]: 
use_sql [yes]: 
use_nosql [no]: 
use_forms [yes]: 
use_socketio [no]: 
Unable to create file 'main.py'
Error message: 'dict object' has no attribute 'create_index'
Context: {
    "cookiecutter": {
        "create_index_view": "yes", 
        "project_name": "findex-gui", 
        "repo_name": "findex-gui", 
        "use_forms": "yes", 
        "use_nosql": "no", 
        "use_socketio": "no", 
        "use_sql": "yes", 
        "version": "0.1"
    }
}

;-(

Running cookiecutter command on windows does not work

I tried installing this repo using cookiecutter on 2 different PC's. They keep failing with the same error.

PS C:\Users<USERNAME><DRIVE>\Desktop\1.Projects> python -m cookiecutter https://github.com/italomaia/flask-empty
[1/17] project_name (Your Project Name): test
[2/17] repo_name (test):
[3/17] version (0.1):
[4/17] use_sql_sqlite (yes): no
[5/17] use_sql_postgres (no):
[6/17] use_sql_mysql (no): yes
[7/17] use_sql_cockroachdb (no):
[8/17] use_nosql_mongodb (no):
[9/17] use_admin (no):
[10/17] use_security (yes):
[11/17] use_rest (yes):
[12/17] use_socketio (yes):
[13/17] use_async_tasks (yes):
[14/17] use_http_mixin (yes):
[15/17] serve_static_files (yes):
[16/17] create_index_view (yes):
[17/17] json_friendly (yes):
File "C:\Users<USER>\AppData\Local\Temp\tmpj8dljd6h.py", line 42
'_output_dir': 'C:\Users/<USERNAME><DRIVE>\Desktop\1.Projects',
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
ERROR: Stopping generation because post_gen_project hook script didn't exit successfully
Hook script failed (exit status: 1)

Not sure what the issue is though.

Debug option in Config file does nothing when using Flask-Script

If you're using Flask-Script, the Debug option does nothing. This can be very frustrating for those who don't know how Flask-Script works. Flask script overrides any Debug config and looks for command line arguments passed when executing runserver. For example,

python manager.py runserver -r -d

This says "Run with no reload and no debug".

You can see how it's hardcoded in Flask-Script itself: https://github.com/joequery/flask-script/blob/master/flask_script.py#L319-320

SyntaxError: invalid syntax: compress = FlaskStaticCompress(app)io = SocketIO()

I am trying out this cookiecutter, being completely new to it.

Upon running: make run-dev I get this error message:

SyntaxError
File "/Repositories/WebApps/flasktest2/extensions.py", line 33
    compress = FlaskStaticCompress(app)io = SocketIO()
                                       ^
SyntaxError: invalid syntax

Traceback (most recent call last)
File "/Repositories/WebApps/flasktest2/venv/lib/python3.9/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/Repositories/WebApps/flasktest2/wsgi.py", line 13, in <module>
app = app_factory(config_obj_path, project_name)
File "/Repositories/WebApps/flasktest2/main.py", line 54, in app_factory
app.setup()
File "/Repositories/WebApps/flasktest2/venv/lib/python3.9/site-packages/empty/app.py", line 114, in setup
self.configure_extensions()
File "/Repositories/WebApps/flasktest2/venv/lib/python3.9/site-packages/empty/app.py", line 205, in configure_extensions
ext = import_string(ext_path)
File "/Repositories/WebApps/flasktest2/venv/lib/python3.9/site-packages/werkzeug/utils.py", line 568, in import_string
__import__(import_name)
File "/Repositories/WebApps/flasktest2/extensions.py", line 33
    compress = FlaskStaticCompress(app)io = SocketIO()
                                       ^
SyntaxError: invalid syntax

index 404

Sorry to say that following the instructions for either venv or docker gave me 404 for index

ValueError: Datastore must be provided

Just hitting return to everything in the default template (after the names) and make run-dev produces this error from flask-security.

I don't see any mention of "datastore" in the config file. It looks like the empty module calls the init_app() method of each extension with no args, and flask_security doesn't like that?

AttributeError: type object 'Config' has no attribute 'DB_NAME'

Hello, i am using the template, in all DB question i put NO because i use MSSQL and the template dont have it.

But i get a error when i try to do the "make run-dev"

File "/mnt/c/Python/contabilium.api.common/config.py", line 94, in Dev
SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/%s.db' % Config.DB_NAME
AttributeError: type object 'Config' has no attribute 'DB_NAME'

i think this is the important fragment of the stacktrace of the error.
i think my NO to use SqlLite is ignored.

Any help can you give me?

Missing files after running cookiecutter

After following the procedures in README.md , I can start the server, but only get a Page Not Found error when I browse to it.

In trying to troubleshoot this, I found that the following files are referred to in README.md but do not exist in the tree that was created:

  1. .venv referred to in this section:
# loads env variables and runs the project in development mode
source .venv && make run-dev
  1. .env referred to in this section:

Be aware that you might need to tweak the environment variables for production mode. **The are available at .env** and Dockerfile. I
3) database.py referred to in this section:

While creating your project, Flask-Empty will ask you if you wish to enable SQL support. Confirm if you do so and Flask-SQLAlchemy will be available and configured through database.py

Note that I requested sqlite support, so if I understand correctly, database.py should have been created?

Error message: 'uses_cockroachdb' is undefined

Maybe I am doing something wrong but my guess is that something is messy with cockroachdb option.

$ cookiecutter https://github.com/italomaia/flask-empty
You've downloaded /home/rodmonte/.cookiecutters/flask-empty before. Is it okay to delete and re-download it? [yes]:
project_name [Your Project Name]: projeto
repo_name [projeto]:
version [0.1]:
use_sql_postgres [no]:
use_sql_mysql [no]:
use_sql_cockroachdb [no]:
use_nosql_mongodb [no]:
use_admin [no]:
use_security [yes]: no
use_rest [yes]:
use_socketio [yes]:
use_async_tasks [yes]:
use_http_mixin [yes]:
create_index_view [yes]:
Unable to create file 'Dockerfile'
Error message: 'uses_cockroachdb' is undefined
Context: {
"cookiecutter": {
"_template": "https://github.com/italomaia/flask-empty",
"create_index_view": "yes",
"project_name": "projeto",
"repo_name": "projeto",
"use_admin": "no",
"use_async_tasks": "yes",
"use_http_mixin": "yes",
"use_nosql_mongodb": "no",
"use_rest": "yes",
"use_security": "no",
"use_socketio": "yes",
"use_sql_cockroachdb": "no",
"use_sql_mysql": "no",
"use_sql_postgres": "no",
"version": "0.1"
}
}

main.py error in configure_blueprints

Hi,

I changed the example and tried adding blueprints to it.. but when registering blueprints as described in the config.py :

BLUEPRINTS = [
'blog.views.app' # or ('blog.views.app', {'url_prefix':'/blog'})
] # each as (blueprint_instance, url_preffix)

The function for registering the blueprints (main.py:51) should handle it as a tuple instead of a dict:

-elif (isinstance(blueprint_config, dict)):
+elif (isinstance(blueprint_config, tuple)):

Alembic integration

Flask-empty needs commands.py integration with alembic. Who lives without migrations nowadays?!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.