Combining React and Flask Routing - flask

I'd like to handle all routing on the client side with two exceptions:
The server should handle any route that begins with /api and serve the files from /dist.
Here's my folder structure:
./
├── Client
│   ├── dist
│   │   └── bundle.js
│   │   └── bundle.css
│   ├── index.html
│   ├── node_modules
│   ├── package.json
│   ├── src
│   │   ├── __tests__
│   │   ├── components
│   │   └── index.tsx
│   ├── tsconfig.json
│   ├── tslint.json
│   ├── webpack.config.js
│   └── yarn.lock
├── README.md
├── app.py
└── requirements.txt
app.py
from flask import Flask, jsonify, render_template
app = Flask(__name__, template_folder="Client")
#app.route('/api/random')
def random_name():
response = {
'randomName': choice(["Ben", "Joe", "Robert", "Amy"])
}
return jsonify(response)
#app.route('/', defaults={'path': ''})
#app.route('/<path:path>')
def index(path):
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
How can I serve bundle.js from index.html?
I've tried using url_for in the index.html but it doesn't work - I get a 404.

Related

How to import the template into a subdirectory of the templates folder in Flask?

Currently I have an API project, based on flask-restful, with documentation page created with OpenAPI (Swagger). I'm trying to create a login page, based on my structure jinja2 can not find the path to the template.
In the login script, I tried to pass the full path to the .html file, in the render_template() function, but did not find the file. Just like adding the parameter template_folder = path/to/file in app=Flask(__name__) and I did not succeed.
My Structure:
├── app
│   ├── __init__.py
│   ├── auth
│   │   ├── __init__.py
│   │   ├── admin.py
│   │   ├── login.py
│   ├── common
│   │   ├── __init__.py
│   │   ├── jwt.py
│   │   ├── request.py
│   │   └── utils.py
│   ├── models
│   │   ├── __init__.py
│   │   ├── core.py
│   │   └── db_app_2.py
│   ├── routes
│   │   ├── __init__.py
│   │   ├── resources.py
│   └── templates
│   ├── docs
│   │   ├── swagger.json
│   │   └── swagger.yaml
│   └── pages
│   ├── base.html
│   ├── login.html
│   └── signup.html
├── app.db
├── config.py
├── main.py
├── migrations
├── requeriments
└── tests
login.py
# -*- coding: utf-8 -*-
from flask import Blueprint, render_template, redirect, url_for
from app.models.core import db
auth = Blueprint('auth', __name__)
#auth.route('/login')
def login():
return render_template('login.html')
#auth.route('/signup')
def signup():
return render_template('signup.html')
__init__.py(main project)
from flask import Blueprint, Flask
from flask_login import LoginManager
from flask_migrate import Migrate
from flask_restful import Api
from config import config
from .models.core import db
from .routes.resources import TwoThings
def create_app(config_name):
app = Flask(__name__, template_folder="/templates/pages")
app.config.from_object(config[config_name])
'''Fixed path for routes the api'''
path_prefix = '/api/v1'
api_bp = Blueprint(path_prefix, __name__)
api = Api(api_bp)
from app.auth.login import auth as auth_blueprint
app.register_blueprint(auth_blueprint, url_prefix=path_prefix)
api.add_resource(Reset, f'{path_prefix}/two_things')
app.register_blueprint(api_bp)
db.init_app(app)
Migrate(app, db)
return app
I need to create a login page, to be accessible by the browser and once logged in redirect to the documentation endpoint.
Try:
return render_template('pages/login.html')
In your login.py.

Celery Cannot find a module in my Django project

I have a Django 2.0 project using celery 4.2.1 and redis 2.10.6. The django project has two apps, memorabilia and face_recognition. I have it all successfully running tasks with django running on my development machine. I uploaded everything to my git server, then installed the apps on my laptop from git, updated all requirements, etc. Both are Ubuntu machines. I am not using django-celery.
When I try to run celery -A MemorabiliaJSON worker -l debug,
I get an exception saying ModuleNotFoundError: No module named 'face_recognition.tasks'
I am not sure how to fix this, as the same code base is running on my development machine.
My file structure is:
├── celery.sh
├── face_recognition
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   ├── models.py
│   ├── __pycache__
│   ├── tasks.py
│   ├── tests.py
│   └── views.py
├── __init__.py
├── manage.py
├── memorabilia
│   ├── admin.py
│   ├── apps.py
│   ├── fields.py
│   ├── fixtures
│   ├── __init__.py
│   ├── logs
│   ├── migrations
│   ├── models.py
│   ├── __pycache__
│   ├── storage.py
│   ├── tasks.py
│   ├── templates
│   ├── tests
│   ├── urls.py
│   ├── validators.py
│   ├── views.py
│   ├── widgets.py
├── MemorabiliaJSON
│   ├── celery.py
│   ├── default_images
│   ├── documents
│   ├── __init__.py
│   ├── __pycache__
│   ├── settings
│   ├── static
│   ├── urls.py
│   ├── views.py
│   ├── wsgi.py
├── __pycache__
│   ├── celery.cpython-36.pyc
│   └── __init__.cpython-36.pyc
├── requirements.txt
└── tests
MemorabiliaJSON/celery.py
# http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from django.apps import apps
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MemorabiliaJSON.settings.tsunami')
app = Celery('MemorabiliaJSON')
app.config_from_object('django.conf:settings', namespace='CELERY')
#app.autodiscover_tasks(lambda: [n.name for n in apps.get_app_configs()])
app.autodiscover_tasks()
#app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
(memorabilia-JSON) mark#octopus:~/python-projects/memorabilia-JSON
face_recognition/__init__.py
default_app_config = 'face_recognition.apps.FaceRecognitionConfig'
memorabilia/__init__.py
default_app_config = 'memorabilia.apps.MemorabiliaConfig'
INSTALLED_APPS has these two apps
'memorabilia.apps.MemorabiliaConfig',
'face_recognition.apps.FaceRecognitionConfig',

Blueprint template folder in flask not working as expected

This is my project structure:
├── run.py
└── test_blueprint
├── __init__.py
├── __init__.pyc
├── mainsite
│   ├── controllers
│   │   ├── controllers.py
│   │   ├── controllers.pyc
│   │   ├── __init__.py
│   │   └── __init__.pyc
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── static
│   │   ├── css
│   │   │   ├── bootstrap.min.css
│   │   │   └── signin.css
│   │   └── js
│   └── templates
│   └── mainsite
│   └── homepage.html
├── static
│   ├── css
│   │   ├── bootstrap.min.css
│   │   └── signin.css
│   └── js
├── templates
│   └── mainsite
│   └── index1.html
└── usermanagement
├── controllers
│   ├── controllers.py
│   ├── controllers.pyc
│   ├── __init__.py
│   └── __init__.pyc
├── __init__.py
├── __init__.pyc
├── static
└── templates
Here I have two blueprints, mainsite and usermanagement. I have registered them in file __init__.py under the test_blueprint folder which is the main folder (one below the blueprint_project folder which has run.py).
__init__ file under test_blueprint
from flask import Flask
app = Flask(__name__)
from test_blueprint.mainsite.controllers.controllers import mod
from test_blueprint.usermanagement.controllers.controllers import mod
app.register_blueprint(mainsite.controllers.controllers.mod, url_prefix="/")
app.register_blueprint(usermanagement.controllers.controllers.mod, url_prefix="/usermanagement")
Now post that I have under each blueprint folder I have created __init__.py in which I have defined Blueprints along with template folder. However, it does not take the template from there. It keeps on throwing error 'template not found'. So, I have created template folder under test_blueprint folder. It perfectly picks index.html from templates/mainsite folder.
Also, if I provide /home/user/flaskenv/blueprint_project/... templates folder which is an absolute path for my template under blueprint folder, it works fine.
Not sure if the bug is in Flask. I saw a video on YouTube and expected my flask project to behave the same. Unfortunately it didn't.
This is what my controller.py/views.py file looks like for mainsite:
from flask import Blueprint, render_template, url_for
mod = Blueprint('mainsite', __name__, static_folder='static',template_folder='templates')
#mod.route("/")
def home():
return render_template('mainsite/homepage.html')
Now if I used os.path.abspath to locate the template folder under the blueprint folder, and then passed that path as variable to template_folder, it works fine.
Now my expectation as per flask documentation is that just mentioning template_folder='templates' should automatically locate templates under the blueprint folder or it entirely defeats the purpose.
I solved by renaming the html file by unique name

Flask Blueprint; No module found named

I'm trying to get Flask Blueprints running in Docker, but having issues with registering Blueprints correct.
I have the following structure:
├── docker-compose.yml
├── nginx
│   ├── Dockerfile
│   └── sites-enabled
│   └── flask_project
└── web
├── Dockerfile
├── __init__.py
├── app.py
├── modules
│   ├── __init__.py
│   └── page
│   ├── __init__.py
│   ├── forms.py
│   ├── models.py
│   ├── views.py
├── requirements.txt
├── static
│   ├── css
│   │   ├── bootstrap.min.css
│   │   └── main.css
│   ├── img
│   └── js
│   └── bootstrap.min.js
└── templates
├── _base.html
└── index.html
app.py contains:
from flask import Flask
from web.modules.page import simple_page
app = Flask(__name__)
app.register_blueprint(simple_page)
if __name__ == '__main__':
print app.url_map
app.run(debug=True)
views.py contains:
from flask import Blueprint
simple_page = Blueprint('simple_page', __name__,
template_folder='templates')
#simple_page.route('/')
def index():
return "Hello world"
__init__.py under page:
from web.modules.page.views import simple_page
The __init__.py files are empty.
The console gives an ImportError: No module named web.modules.page
Thanks for your time.
Look like is structure problem, you can reference from here: https://www.digitalocean.com/community/tutorials/how-to-structure-large-flask-applications
The following is my example, hope it can help for you:
├── app
│   ├── __init__.py
│   ├── main
│   │   ├── __init__.py
│   │   └── views.py
│   ├── models
│   │   └── __init__.py
│   ├── static
│   │   ├── css
│   │   ├── js
│   │   ├── img
│   │   └── file
│   ├── templates
│   │   └── index.html
└── master.py
app/__init__.py
from flask import Flask
from app.main import main
def create_app():
app = Flask(__name__)
app.register_blueprint(main)
return app
app/main/__init__.py
from flask import Blueprint
main = Blueprint('main', __name__)
from app.main import views
master.py
from app import create_app
if __name__ == '__main__':
app = create_app()
app.run(host='0.0.0.0', port=8000, threaded=True)

Can't make test execute

Folders structure:
.
├── db.sqlite3
├── homepage
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── manage.py
├── photoarchive
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── somesite
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-34.pyc
│   │   ├── settings.cpython-34.pyc
│   │   ├── urls.cpython-34.pyc
│   │   └── wsgi.cpython-34.pyc
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── tests
├── functional_test.py
├── __init__.py
├── __pycache__
│   ├── functional_test.cpython-34.pyc
│   ├── __init__.cpython-34.pyc
│   └── validators.cpython-34.pyc
└── validators.py
functional_test.py
from selenium import webdriver
from django.test import TestCase
import pdb
class HomePageTest(TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
pdb.set_trace()
def tearDown(self):
self.browser.quit()
def test_home_page(self):
#Edith goes to home page.
self.browser.get("http://localhost:8000")
#Edith sees "Hello, world" in the browser title.
estimated_browser_title ="Hello, world"
real_browswer_title = self.browser.title
self.assertIn(estimated_browser_title, real_browswer_title)
I run the test:
(venv) michael#michael:~/workspace/mysite/somesite$ python manage.py test tests
Creating test database for alias 'default'...
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
Destroying test database for alias 'default'...
Could you help me understand why my tests are not executed. I set a pdb breakpoint. The interpreter doesn't stop at that breakpoint. Well, tests are ignored.
Could you give me a kick here?
Django's test runner will only discover tests inside apps that are included in INSTALLED_APPS. Rather than putting your code in a functional_test.py file inside a tests directory, you should put it in a file called tests.py inside one of the app directories.