I have the following file structure:
.
├── app
│ ├── api_routes
│ │ ├── forms.py
│ │ ├── __init__.py
│ │ └── routes.py
│ ├── __init__.py
│ ├── main_routes
│ │ ├── forms.py
│ │ ├── __init__.py
│ │ └── routes.py
│ ├── models.py
│ ├── static
│ │ └── styles.css
│ ├── templates
│ │ └── base.html
│ └── uploads
│ └── 10_0_0.jpg
├── application.py
└── config.py
In my config.py I have this:
class Config(object):
UPLOAD_FOLDER = 'uploads/'
When I'm saving an uploaded file, and then sending it back to the user (just as example) I'm using:
fname = 'foo.jpg'
fname_save = os.path.join(current_app.root_path, current_app.config['UPLOAD_FOLDER'], fname)
fname_retr = os.path.join(current_app.config['UPLOAD_FOLDER'], fname)
file.save(fname_save)
return send_from_directory(os.path.dirname(fname_retr),
os.path.basename(fname_retr))
Having different names for the upload folder in the cwd (where the file is saved), and the folder the flask module is running (app/), is a bit tedious. Are there any more elegant solutions than my current one to solve this issue?
What I would do this :
#app.route('/upload', methods=['POST'])
def myroute():
fname = 'foo.jpg'
file = request.file[0] # not save at all
send_back_file = io.BytesIO(file.read())
file.seek(0)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], fname))
return send_file(send_back_file, attachment_filename=fname, as_attachement=True)
Resource :
http://flask.pocoo.org/snippets/32/
http://flask.pocoo.org/docs/0.12/patterns/fileuploads/
Related
I know this is something dumb, but I'm a new programmer and I've been smacking my head against it for 2 hours and you will likely see it in 2 seconds so...
View AllEncountersListView which has declared template_name = 'encounter_list_all.html' is using instead 'encounter_list.html'. I know the view is being called since it prints to terminal as expected. Thanks for your time.
views.py:
class AllEncountersListView(generic.ListView):
model = Encounter
paginate_by = 20
template_name = 'encounters_list_all.html'
def get_queryset(self):
print('in allEncounterListView') #to prove the correct view is being called
return Encounter.objects.filter(user=self.request.user).order_by('-encounter_date')
urls.py:
urlpatterns = [
path('',views.index, name='index'),
path('openencounter/', views.open_encounter, name='openencounter'),
path('myencounters/', views.EncountersByUserListView.as_view(), name='my-encounters'),
path('allencounters/', views.AllEncountersListView.as_view(), name='all-encounters'),
path('encounter/<int:pk>', views.EncounterDetailView.as_view(), name = 'encounter-detail'),
path('todaysencounters/', views.TodaysEncountersListView.as_view(), name='todays-encounters'),
path('logout/', views.logout_view, name='logout'),
path('export/', views.export_data_view, name = 'export'),
]
file tree:
── Aents4
│ ├── __init__.py
│ ├── __pycache__
│ ├── asgi.py
│ ├── settings.py
│ ├── templates
│ │ ├── registration
│ │ │ └── login.html
│ │ └── temp
│ ├── urls.py
│ └── wsgi.py
├── db.sqlite3
├── encounters
│ ├── __init__.py
│ ├── __pycache__
│ ├── admin.py
│ ├── apps.py
│ ├── forms.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── 0002_auto_20210926_1548.py
│ │ ├── 0003_alter_encounter_encounter_date.py
│ │ ├── 0004_auto_20210927_1704.py
│ │ ├── 0005_animal_max_daily.py
│ │ ├── 0006_auto_20210928_1157.py
│ │ ├── __init__.py
│ │ └── __pycache__
│ ├── models.py
│ ├── registration
│ │ └── login.html
│ ├── static
│ │ └── styles.css
│ ├── templates
│ │ ├── base_generic.html
│ │ ├── encounters
│ │ │ ├── encounter_detail.html
│ │ │ ├── encounter_form.html
│ │ │ ├── encounter_list.html
│ │ │ ├── encounters_list_all.html
│ │ │ ├── encounter_update_form.html
│ │ │ └── encounters_list_by_user.html
│ │ ├── index.html
│ │ ├── openencounter.html
│ │ └── registration
│ │ └── login.html
│ ├── tests.py
│ ├── urls.py
│ └── views.py
└── manage.py
class AllEncountersListView(generic.ListView):
model = Encounter
paginate_by = 20
template_name = "encounters/encounters_list_all.html"
def get_queryset(self):
return Encounter.objects.filter(user=self.request.user).order_by('-encounter_date')
Try this please if you didn't already. Usually, when we are configuring our settings.py, we make it look in the templates directory for files, but you have subdirectory encounters which contain the template files. Try to target that subdirectory with this line:
template_name = "encounters/encounters_list_all.html"
I hope this helps; please inform us about result so we can try other solutions if needed.
Maybe it didn't throw any errors because the Django class views has that functionality such that when template name is not specified it looks at the class name and tries to figure out which template to render; maybe that is why that other template is being used. Check the Django documentation for more information.
I just moved tests.py file to a new directory called tests, then I added __init__.py file therein, but as I run the test python manage.py test it says ran 0 tests in 0.000s. How to solve it?
I don't know how to show my files like most do, but here is an image!
This app is also added in settings.py
Thanks
edit:
this is a sample of test_models.py
from django.test import TestCase
# Create your tests here.
from django.test import TestCase
from django.urls import reverse
from board.models import Board
from board.views import board_topics
class HomeTest(TestCase):
def home_test_case(self):
url = reverse('home')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
class BoardTest(TestCase):
def setup(self):
Board.objects.create(title='Hello world',
description='My first Django app!')
def board_topics_status_code(self):
url = reverse('board_topics', kwargs={id: 1})
response = self.client.get(url)
return self.assertEqual(response.status_code, 200)
def board_topics_status_code_not_found(self):
url = reverse('board_topics', kwargs={id: 123})
response = self.client.get(url)
return assertEqual(response.status_code, 200)
def resolve_url_to_specific_fun(self):
url = resolve('board/1/')
return assertEqual(view.func, board_topics)
def HomeTests(TestCase):
def setUp(self):
self.board = Board.objects.create(
title='Django', description='Django Desc')
url = reverse('home')
self.response = self.client.get(url)
def home_test_view_status_code(self):
self.assertEqual(self.response.status_code, 200)
def home_test_func(self):
view = resolve('/')
self.assertEqual(view.func, home)
def test_home_contains_link_to_topics_page(self):
board_topics_url = reverse(
'board_topics', kwargs={'id': self.board.pk})
self.assertContains(self.response, 'href={0}'.format(board_topics_url))
All your tests must have the test_ prefix attached. Rename all your tests adding that to the name.
For example:
def test_board_topics_status_code(self):
url = reverse('board_topics', kwargs={id: 1})
response = self.client.get(url)
return self.assertEqual(response.status_code, 200)
Also, you need to change def HomeTests(TestCase): to class HomeTests(TestCase):, that's why your last test is named correctly but it is still not being discovered.
There are 2 ways you can keep your tests in your Project. I prefer the
1st one.
1. Your development code contains all of your tests. This way it's easier to add a new test when you write development code and your tests now ships with your development code.
Project
├── __init__.py
├── api
│ ├── v1
│ │ ├── tests
│ │ │ ├── __init__.py
│ │ │ ├── test_serializers.py
│ │ │ └── test_views.py
│ │ ├── __init__.py
│ │ ├── serializers.py
│ │ ├── urls.py
│ │ └── views.py
│ ├── v2
│ │ ├── tests
│ │ │ ├── __init__.py
│ │ │ ├── test_serializers.py
│ │ │ └── test_views.py
│ │ ├── __init__.py
│ │ ├── serializers.py
│ │ ├── urls.py
│ │ └── views.py
│ ├── __init__.py
│ ├── serializers.py
│ └── urls.py
├── models
│ ├── tests
│ │ ├── __init__.py
│ │ ├── test_data_structures.py
│ │ ├── test_miscellaneous_models.py
│ │ ├── test_models.py
│ ├── __init__.py
│ ├── models.py
│ ├── data_structures.py
│ └── miscellaneous_models.py
├── resume_handler
│ ├── tests
│ │ ├── __init__.py
│ │ ├── test_handlers.py
│ │ ├── test_managers.py
│ │ ├── test_parsers.py
│ │ ├── test_uploaders.py
│ │ └── test_validators.py
│ ├── __init__.py
│ ├── handlers.py
│ ├── managers.py
│ ├── parsers.py
│ ├── uploaders.py
│ └── validators.py
├── tasks
│ ├── tests
│ │ ├── __init__.py
│ │ └── test_tasks.py
│ ├── __init__.py
│ ├── general.py
│ └── model_tasks.py
├── tests
│ └── test_utils.py
└── utils.py
2. Another way is to put a test folder separate from the project folder. This test folder maintains the same hierarchy as of the project folder. This keeps the test code separate from the development code.
Project
├── api
│ ├── v1
│ │ └── more code files ...
│ ├── v2
│ │ └── more code files ...
│ └── v3
│ └── more code files ...
├── choices
├── constants
├── models
│ ├── data_filters
│ ├── querysets
│ └── more code files ...
├── resume_builder
│ └── more code files ...
├── resume_handler
│ └── more code files ...
├── tasks
│ └── more code files ...
└── more code files ...
Now in the same directory in which the Project folder is present create a test folder which maintains the same hierarchy but only contain the corresponding tests files.
test
├── api
│ ├── v1
│ │ └── test files ...
│ ├── v2
│ │ └── test files ...
│ └── v3
│ └── test files ...
├── choices
├── constants
├── models
│ ├── data_filters
│ ├── querysets
│ └── test files ...
├── resume_builder
│ └── test files ...
├── resume_handler
│ └── test files ...
├── tasks
│ └── test files ...
└── test files ...
Flask: app.register_blueprint works fine when run using the builtin app.run. However fails when tied to apache. I am getting a 404 error when I access the url
http://ipadddress/register - 404 Not Found
I have setup a Flask App with Apache2 and wsgi configuration. Below is the code. I have done the apache setup using Digital Ocean - Apache Flask configuration on debian systems
init.py
from flask import Flask, render_template
from register.registeration import account_api
app = Flask(__name__)
app.register_blueprint(account_api)
#app.route('/')
def home():
return render_template('index.html')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8080, debug=True)
register/registration.py
from flask import Blueprint, render_template
account_api = Blueprint('account_api', __name__)
#account_api.route('/register')
def register():
return render_template('register.html')
flaskapp.wsgi
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/home/pi/ReSTServices/env/")
from FlaskApp import app as application
application.secret_key = 'MyHappyNewsWithHacker'
Project Structure
├── flaskapp.wsgi
├── __init__.py
├── register
│ ├── __init__.py
│ └── registeration.py
├── static
│ └── dist
│ ├── css
│ │ ├── bootstrap.css
│ │ ├── bootstrap.css.map
│ │ ├── bootstrap.min.css
│ │ ├── bootstrap.min.css.map
│ │ ├── bootstrap-theme.css
│ │ ├── bootstrap-theme.css.map
│ │ ├── bootstrap-theme.min.css
│ │ ├── bootstrap-theme.min.css.map
│ │ ├── font-awesome.min.css
│ │ ├── sticky_footer.css
│ │ └── style.css
│ ├── fonts
│ │ ├── FontAwesome.otf
│ │ ├── fontawesome-webfont.eot
│ │ ├── fontawesome-webfont.svg
│ │ ├── fontawesome-webfont.ttf
│ │ ├── fontawesome-webfont.woff
│ │ ├── fontawesome-webfont.woff2
│ │ ├── glyphicons-halflings-regular.eot
│ │ ├── glyphicons-halflings-regular.svg
│ │ ├── glyphicons-halflings-regular.ttf
│ │ ├── glyphicons-halflings-regular.woff
│ │ └── glyphicons-halflings-regular.woff2
│ ├── img
│ │ └── rpi.png
│ └── js
│ ├── bootstrap.js
│ ├── bootstrap.min.js
│ └── npm.js
└── templates
├── index.html
└── register.html
I have a try except block in one of my Django view functions that will delete a User object that was created in the try block if anything should fail. When I attempt to delete the User I get this error message.
OperationalError: no such table: reversion_revision
The same issue happens in the Django admin as well. I am having issues finding similar cases of this OperationalError happening to other people, and am not sure why it is happening. All the other objects that I am deleting in the except block delete without any issues.
#csrf_exempt
def signup(request):
# """Register a new account with a new org."""
if request.is_ajax():
if request.method == "POST":
form = SignUp(requestPost(request))
if form.is_valid():
cleaned_data = form.cleaned_data
email = cleaned_data['email']
password = cleaned_data['password']
org_name = cleaned_data['org_name']
org_username = cleaned_data['org_username']
if cleaned_data['token']:
invite_token = cleaned_data['token']
else:
invite_token = cleaned_data['invite']
try:
account = Account.objects.create(email=email, password=password)
x = email[:30]
userExists = User.objects.filter(username=email[:30])
if not userExists:
if len(email) < 30:
user = User.objects.create_user(email, email, password)
else:
email = email[:30]
user = User.objects.create_user(email, email, password)
if invite_token:
if ThreadInvite.objects.filter(token=invite_token):
invitation = ThreadInvite.objects.get(token=invite_token)
thread = Thread.objects.get(id=invitation.thread.id)
ThreadMember.objects.create(thread=thread, account=account)
else:
invitation = OrgInvite.objects.get(token=invite_token)
if invitation.used:
raise Exception("invitation code is invalid")
org = Org.objects.get(id=invitation.org.id)
OrgMember.objects.create(org=org, account=account)
invitation.used = False
invitation.save()
add_to_welcome(org_id=org.id, account_id=account.id)
if org_username and org_name:
org = Org.objects.create(name=org_name, username=org_username,
actor=account)
OrgMember.objects.create(account=account, org=org)
Thread.objects.create(name='welcome', account=account, owner=account, org=org,
purpose='To welcome new members to the team.')
add_to_welcome(org_id=org.id, account_id=account.id)
login(request)
md = mandrill.Mandrill(settings.MANDRILL_API_KEY)
t = invite_token.replace(' ', '+')
url = "https://localhost:8000/verify/{}".format(t)
message = {
'global_merge_vars': [
{
'name': 'VERIFICATION_URL',
'content': url
},
],
'to': [
{
'email': 'tim#millcreeksoftware.biz',
},
],
'subject': 'Welcome to Human Link',
}
message['from_name'] = message.get('from_name', 'Humanlink')
message['from_email'] = message.get('from_email',
'support#humanlink.co')
try:
md.messages.send_template(
template_name='humanlink-welcome', message=message,
template_content=[], async=True)
except mandrill.Error as e:
logging.exception(e)
raise Exception(e)
context = {
'message': 'ok'
}
return composeJsonResponse(200, "", context)
except Exception, e:
logging.error(e)
Account.objects.filter(email=email, password=password).delete()
User.objects.filter(username=email[:30]).delete()
Org.objects.filter(name=org_name, username=org_username).delete()
Structure
├── account
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── admin.py
│ ├── admin.pyc
│ ├── apps.py
│ ├── forms.py
│ ├── forms.pyc
│ ├── migrations
│ ├── models.py
│ ├── models.pyc
│ ├── tests.py
│ ├── tests.pyc
│ ├── urls.py
│ ├── urls.pyc
│ ├── views.py
│ └── views.pyc
├── api_helpers.py
├── api_helpers.pyc
├── app
│ └── components
├── bower.json
├── bower_components
│ ├── angular
│ ├── angular-animate
│ ├── angular-bootstrap
│ ├── angular-cookies
│ ├── angular-messages
│ ├── angular-sanitize
│ ├── angular-scroll-glue
│ ├── angular-touch
│ ├── angular-ui-router
│ ├── bootstrap
│ ├── checklist-model
│ ├── font-awesome
│ ├── jquery
│ ├── moment
│ ├── pusher-websocket-iso
│ └── underscore
├── cron_tasks.py
├── gulpfile.js
├── logs
│ └── readme.txt
├── manage.py
├── message
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── admin.py
│ ├── admin.pyc
│ ├── forms.py
│ ├── forms.pyc
│ ├── migrations
│ ├── models.py
│ ├── models.pyc
│ ├── urls.py
│ ├── urls.pyc
│ ├── views.py
│ └── views.pyc
|
├── org
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── admin.py
│ ├── admin.pyc
│ ├── forms.py
│ ├── forms.pyc
│ ├── migrations
│ ├── models.py
│ ├── models.pyc
│ ├── tests.py
│ ├── tests.pyc
│ ├── urls.py
│ ├── urls.pyc
│ ├── views.py
│ └── views.pyc
├── package.json
├── readme.txt
├── settings
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── base.py
│ ├── base.pyc
│ ├── cron.py
│ ├── development.py
│ ├── development.pyc
│ └── production.py
├── sqlite3
│ └── local.db
├── stylesheets
│ └── less
├── templates
│ ├── accounts
│ ├── admin
│ ├── dashboard
│ ├── footer.html
│ ├── home
│ ├── layouts
│ ├── nav.html
│ ├── pages
│ ├── settings
│ ├── shared
│ ├── site-alert.html
│ └── site.html
├── third_party
│ ├── classytags
│ ├── dateutil
│ ├── django_pusher
│ ├── itsdangerous.py
│ ├── itsdangerous.pyc
│ ├── mandrill.py
│ ├── mandrill.pyc
│ ├── mptt
│ ├── pusher
│ ├── requests
│ ├── reversion
│ ├── six.py
│ ├── six.pyc
│ ├── suit
│ └── werkzeug
├── utility.pyc
├── webapp
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── static
│ ├── urls.py
│ ├── urls.pyc
│ ├── views.py
│ ├── views.pyc
│ ├── wsgi.py
│ └── wsgi.pyc
└── webapp_admin
├── __init__.py
├── __init__.pyc
└── static
Problem here is not in your code but in your database state. Looks like you added django reversion app. Which adds new Models in your project. Run
python manage.py syncdb
or if you in 1.8+
python manage.py migrate
Update
If this doesn't help than there are no migrations for your 3rd-party app you need to first create them with
python manage.py makemigrations name_3rd_party_app
Be careful with creating migrations on 3rd-party apps. When you run makemigrations it creates migrations in 3rd-party app package. So it won't be in your code. And after you deploy it, or other user uses it there are will not be this migrations. So you need to supply custom path for created migrations with https://docs.djangoproject.com/en/1.9/ref/settings/#migration-modules
And then run migrate
Try running
./manage.py makemigrations revisions
then
./manage.py migrate
or just delete the db file and start over with
./manage.py migrate
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