why url cannot be generated after use blueprint - python

My current project looks like this:
├── __init__.py
├── pages
├── settings.py
├── static
├── templates
│   ├── article.html
│   ├── base.html
│   ├── index.html
│   └── posts.html
├── view
│   ├── article.py
│   ├── home.py
│   ├── index.py
│   └── postwall.py
I breaked views.py(no longer in the project) into files and those files cannot generate url dynamically anymore. What i had in article.py is:
from flask import Blueprint, render_template
from app import articles
article = Blueprint('article',__name__)
#article.route('/article/<path:path>/')
def page(path):
article = articles.get_or_404(path)
return render_template('article.html',page=article)
Meanwhile, posts.html which offers the link button to articles doesn't work anymore:
More ->
What is the problem?Did I miss something in the blueprint file?

solved. change
More ->
to
More ->
forgot to add blueprint name

Related

Relative import error with flask

According to this, I am trying to run my flask web application from my com_profiler directory as python -m api.index, python -m api.index.py, python api/index.py. But none of these are working. The errors I am getting are in the order -
-> ValueError: attempted relative import beyond top-level package
-> attempted relative import beyond top-level package
-> SystemError: Parent module '' not loaded, cannot perform relative import
Directory Structure:
comp_profiler/
├── api
│   ├── bootstrap.sh
│   ├── index.py
│   └── __init__.py
├── __init__.py
├── pipelines.py
├── random_useragent.py
├── requirements.txt
├── scrapy.cfg
├── spiders
│   ├── __init__.py
│   ├── content_handler.py
│   ├── core_spider.py
│   ├── middlewares.py
│   ├── scrapper
│   │   ├── __init__.py
│   │   ├── corporatedir.py
│   │   ├── craft.py
│   │   ├── tofler.py
│   │   └── zaubacorp.py
│   ├── scrapper.py
│   ├── seed_list_generator.py
│   ├── settings.py
│   └── utility.py
index.py
from flask import Flask, request, jsonify
from ..spiders.seed_list_generator import SeedListGenerator
app = Flask(__name__)
#app.route("/start-spider")
def hello_world():
spider = SeedListGenerator()
company_name = request.get_json()
print(company_name)
return "Hello world"
if __name__ == "__main__":
app.run()
I also tried running it from api directory, but no success.
Kindly let me know if I am missing something with flask setup, as I am just starting up with flask.
Update: I want to integrate SeedListGenerator as API call. Kindly suggest.
Thanks in advance.

What's the best practice when extending an application's template?

I've recently started studying Django(ver 1.9), and have a question about templates inheritance.
Suppose I have a Django project named mysite and an app named myapp.
And I created base template named base.html and another one named child.html, which inherits base.html.
So directory structure is like this:
(project root)
├── mysite
│   ├── settings.py
│   ├── urls.py
│   └── ...
├── myapp
│   ├── models.py
│   ├── views.py
│   ├── ...
│   └── templates
│   └── myapp
│   ├── base.html
│   └── child.html
└── manage.py
In this situation, I can inherit base.html like this.
<!-- on top of `child.html` -->
{% extends "myapp/base.html" %}
What I'm wondering is, I'm hard-coding the application name.
Are there any other ways of writing that avoid hard-coding the app name?
Or, it's OK and I don't need to worry about?
I came up with some workarounds.
1) Place base.html directly under templates directory
├── myapp
│   ├── models.py
│   ├── views.py
│   ├── ...
│   └── templates
│   ├── base.html # Here!
│   └── myapp
│   └── child.html
--> I think it causes file name crashing between applications.
2) Place base.html under project templates directory
-->In this case I don't want to share base.html between applications.
(base.html here is only for myapp, not other applications)
Both your base template and your child template are specific to your app, so both should live in the same myapp/ subdirectory. It's entirely acceptable to hard-code the dependency on myapp/base.html.
How about
|── myapp
│ ├── models.py
│ ├── views.py
│ ├── ...
│ └── templates
│ ├── base.html # Here!
│ └── child.html
│
then use
<!-- on top of `child.html` -->
{% extends "base.html" %}
Then dynamically changing your Template directory at the beginning of each views.py file.
from django.conf import settings
settings.TEMPLATE_DIRS =(os.path.join(settings.BASE_DIR,'myapp/templates').replace('\\','/'),)
You will have to do the same for every one of your apps.

Flask importing files through Pycharm

Following microblog tutorial on Flask: http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
In Pycharm, no matter how I structure or name the files, I cannot get the dev server to run if I separate the code and import the files. I also can't get it to inherit the codes no matter where I move the init, views, run files. The only way for me to get the server to run is to have all the commands execute on the same file. What am I doing wrong?
I have it setup as:
Project 1 > app(directory) > tmp(directory) > run.py(file)
app(directory) > static(directory) > templates(directory) > init.py(file) > views.py(file) (I have tried different arrangements.)
Inside views.py:
from app import app
Inside run.py:
from app import app
Inside init.py:
from flask import Flask
from app import views
(I have tried many different combinations such as from app import app.views. from app import views as app_views. I have also tried renaming the directories/files, nothing is working.)
Build the new project with PyCharm, it will create a virtual environment for you. Then put these into a run.py in a root of your
a project like that (don't forget to turn debugging mode off in prod)
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
Set up init.py file inside you 'app':
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
bcrypt.init_app(app)
login_manager.init_app(app)
mail.init_app(app)
Store your credentials into Config class:
class Config:
SECRET_KEY = 'your key... '
SQLALCHEMY_DATABASE_URI = 'your db...'
SQLALCHEMY_TRACK_MODIFICATIONS = False
MAIL_SERVER = 'smtp.google.com'
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USERNAME = 'your email'
MAIL_PASSWORD = 'email password'
Structure your project, placing an empty init.py into each directory( accordingly to your architecture). Here is an example below, how to structure your project in Flask. It runs with no problem on
.
├── README.md
├── app
│   ├── __init__.py
│   ├── config.py
│   ├── errors
│   │   ├── 403.html
│   │   ├── 404.html
│   │   ├── 500.html
│   │   ├── __init__.py
│   │   └── handlers.py
│   ├── main
│   │   ├── __init__.py
│   │   └── routes.py
│   ├── models.py
│   ├── posts
│   │   ├── __init__.py
│   │   ├── forms.py
│   │   └── routes.py
│   ├── site.db
│   ├── static
│   │   ├── main.css
│   │   └── profile_pics
│   │   ├── 3c4feb2bb50d90df.png
│   │   ├── ba3d328163a8125e.png
│   │   └── default.jpg
│   ├── templates
│   │   ├── about.html
│   │   ├── account.html
│   │   ├── create_post.html
│   │   ├── home.html
│   │   ├── layout.html
│   │   ├── login.html
│   │   ├── post.html
│   │   ├── register.html
│   │   ├── reset_request.html
│   │   ├── reset_token.html
│   │   └── user_posts.html
│   └── users
│   ├── __init__.py
│   ├── forms.py
│   ├── routes.py
│   └── utils.py
└── run.py

Flask url_for incorrectly links to static pages outside of templates

I'm currently in the process of moving all of my static files to S3, as well as allowing some image uploads to my site. In general this is going fantastically. I got all of my existing css and js files up to S3 with no hassle, however I'm having some trouble with uploading images and saving them to S3.
Specifically this is how I'm handling file uploads within my view:
image_file = request.files["imageurl"]
if image_file and allowed_file(image_file.filename):
fn = "products/%s" % secure_filename(image_title + "." + image_file.filename.split(".")[-1])
image_file.save(url_for('static', filename=fn))
else:
response = app.make_response(render_template(
'admin/newImage.html',
title=title,
error="That Image file is invalid.")
)
return response
Which is all wrapping in a POST request handler. The problem here is that the url_for('static') fails to link to the correct path, and so I get an IOError anytime I try to save an image like this.
Normally I would assume I was just doing something silly with my directory structure, but the same pattern of url_for works perfectly for files in my static directory. Any ideas on how to remedy this? Here's my directory structure (trimmed down for viewing)
├── SpoolEngine
│   ├── admin.py
│   ├── __init__.py
│   ├── templates
│   │   ├── admin
│   │   │   ├── base.html
│   │   ├── base.html
│   │   ├── _forms.html
│   │   ├── posts
│   │   │   ├── complete.html
│   │   └── super_user
│   │   ├── base.html
│   ├── users.py
│   └── views.py
└── static
├── css
│   ├── admin.css
│   └── zebraTable.css
├── img
│   └── subtle_grunge.png
├── js
│   ├── compatibility.js
│   ├── list.js
│   ├── login.js
│   └── profiler.js
└── products
And for reference, url_for works perfectly within /static/css and links to the wrong url from admin.py Any ideas?
url_for returns an url path. Not a filesystem path.
So you're trying to save your file at /static/something which, for the system, means a path starting from the root of your filesystem, not your application path.
You can create the static path for your file with something like this
static_path_to_save = os.path.join([app.root_path, '/static', fn])
Just a side note, when dealing with uploads, remember to sanityze all the paths and to double check the destination. Best practices applies, like stripping slashes if you use the filename provided by the user (best is if you generate the filename).
In your code I see also a problem if 2 users uploads a file with the same name, overwriting each other. But this is probably safe in your context.

Common folder/file structure in Flask app [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 months ago.
The community reviewed whether to reopen this question 3 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I have just created a flask application and so far I have a router for my "Hello world!" template.
I would like to add a little (a lot) more functionality, but I wonder how I should structure the app directory.
What's the most common way of structuring a Flask app?
For instance, should I create a routes.py for all my routes?
Where does the SQLAlchemy stuff go?
Should models be in models.py?
You should check out the Larger Applications page in the Patterns section of the Flask docs: http://flask.pocoo.org/docs/patterns/packages/. It seems to be the model that most people follow when their application calls for a package instead of a module.
I believe views.py is what you are calling routes.py. After that, models would go in models.py, forms would go in forms.py, etc.
An example of a FlaskApp directory:
/yourapp
/run.py
/config.py
/app
/__init__.py
/views.py
/models.py
/static/
/main.css
/templates/
/base.html
/requirements.txt
/yourappenv
run.py - contains the actual python code that will import the app and start the development server.
config.py - stores configurations for your app.
__init__.py - initializes your application creating a Flask app instance.
views.py - this is where routes are defined.
models.py - this is where you define models for your application.
static - contains static files i.e. CSS, Javascript, images
templates - this is where you store your html templates i.e. index.html, layout.html
requirements.txt - this is where you store your package dependancies, you can use pip
yourappenv - your virtual environment for development
I would say if you split the application use divisional rather than functional structure.
I advocate this because you are more likely to work on 1 of these divisional components at any one time.
This type of structure lends itself well on marketplace or SaaS apps where different user groups use a different type of views. API only flask app I might use functional splitting.
Here are examples from Flask Blueprints. Blueprints are essentially documented advice how to split Flask application for more manageable pieces. More on this at : http://exploreflask.com/en/latest/blueprints.html
Here is an example of divisional splitting. See how each feature is grouped together.
yourapp/
__init__.py
admin/
__init__.py
views.py
static/
templates/
home/
__init__.py
views.py
static/
templates/
control_panel/
__init__.py
views.py
static/
templates/
models.py
Here is the functional example >
yourapp/
__init__.py
static/
templates/
home/
control_panel/
admin/
views/
__init__.py
home.py
control_panel.py
admin.py
models.py
I think flask is micro framework and now you must decide how create files and folders.
i use this way :
flask folders and files structure -> https://gist.github.com/4545740
this is near Django structure
i suggest you see some project to give you what you want
danjac / newsmeme — Bitbucket -> https://bitbucket.org/danjac/newsmeme/overview
sean-/flask-skeleton · GitHub -> https://github.com/sean-/flask-skeleton
Anyone looking for a simple beginner-friendly structure for the flask project may find this helpful:
|__movies
|__run.py
|__app
├── templates
│ └── index.html
│ └── signup.html
└── __init__.py
└── routes.py
Here 'movies' is the name given for the main application. It contains 'run.py' and a folder called 'app'.
'app' folder contains all necessary flask files such as 'templates' folder, '__init __.py', and 'routes.py'.
Contents of:
run.py:
from app import app
__init.py__:
from flask import Flask
app = Flask(__name__)
from app import routes
app.run(debug=True)
routes.py:
from app import app
#app.route('/')
#app.route('/index')
def index():
return "Hello, World!"
Beauty of flask lies in its flexibility. You can build django like project-structure easily. Django popularized abstraction of features in apps and making them reusable but it can be a overkill for many projects.
But with flask you can go either way. Write reusable apps or write simple apps. Check these cookiecutter skeletons -
minimal skeleton
myproject
├── config.py
├── instance
│   └── config.py
├── myproject
│   ├── commands.py
│   ├── controllers.py
│   ├── extensions.py
│   ├── forms.py
│   ├── __init__.py
│   ├── models.py
│   ├── routes.py
│   └── ui
│   ├── static
│   │   ├── css
│   │   │   └── styles.css
│   │   └── js
│   │   └── custom.js
│   └── templates
│   └── index.html
├── README.md
├── requirements.txt
└── wsgi.py
django like skeleton
myproject
├── config.py
├── development.py
├── instance
│   └── config.py
├── myproject
│   ├── auth
│   │   ├── controllers.py
│   │   ├── forms.py
│   │   ├── __init__.py
│   │   ├── models.py
│   │   └── routes.py
│   ├── helpers
│   │   ├── controllers.py
│   │   ├── __init__.py
│   │   └── models.py
│   ├── __init__.py
│   └── ui
│   └── templates
│   ├── 404.html
│   ├── 500.html
│   └── base.html
├── README.md
├── requirements.txt
├── tests
│   ├── auth
│   │   ├── __init__.py
│   │   └── test_controllers.py
│   └── __init__.py
└── wsgi.py
This is an excellent article on this.
You could get inspired by the cookiecutter templates here to jumpstart your app development
https://github.com/imwilsonxu/fbone
https://github.com/cookiecutter-flask/cookiecutter-flask
Here is the basic file structure for flask I use regularly.
yourapp/
static/
js
css
img
templates/
home.html
index.html
app.py
static folder contains all the static files of the website.
The templates folder contains all the HTML pages.
and app.py contains your python views.
I decided to nest the source code folder under src/.
my_flask_app (project folder)
├── app.py
├── setup.py
├── src/
│ ├── my_flask_app/ (source code folder)
│ │ ├── config.py
│ │ ├── errors.py
│ │ ├── forms.py
│ │ ├── __init__.py
│ │ ├── models.py
│ │ ├── routes.py
│ │ ├── static/
│ │ └── templates/
│ └── my_flask_app.egg-info/
|
└── tests/ (test folder)
Because of this, I added package_dir={'': 'src'} in setup.py.
good idea is to goole for sceletons/template projects on github
for example you can look at this
https://github.com/xen/flask-project-template
https://github.com/upperlinecode/flaskproject
https://github.com/alisezer/flask-template
In flask we can maintain the mvc structure like as separate all thinks
for example
1 Templets folder contains all html files
2 Static folder contains all css and boostrap related files
3 User defined db folder for db connection and crud operations
4 User defined Model folder for accessing/ binding the data from Templets/front- end to db/back-end connectivity
and after the main activity file
for reference flask file structure link as follow
https://flask.palletsprojects.com/en/1.1.x/tutorial/layout/
For larger projects here's what my directory structure looks like
app_name(root folder)
│ .env
│ .gitignore
│ .gitattributes
│ README.MD
│ pyproject.toml
│
└── app(source code)
│ │ __init__.py
│ │ __main__.py
│ │ db.py
│ │ auth.py
│ │ forms.py
│ │ utils.py
│ │ config.py
│ │
│ └─── routes
│ __init__.py
│ views.py
│ api.py
│ auth.py
│
└─ resources
│ |─── static
│ │ css
│ │ js
│ │ images
│ │
│ └─── templates
│ base
| components
│
└─ tests
└─ venv
└─ docs

Categories