I have the following package structure
This is my code in home.py
import os
from flask import Blueprint, render_template, request, flash, url_for
from .. import db
from ..models.home import Summary
from ..forms.home import SummarizerForm
from ..processing.summarizer import Summarizer
from ..helpers import flash_errors
from ..processing.newsbot import NewsBot
home = Blueprint('home', __name__)
#home.route('/', methods=['GET', 'POST'])
def index():
summary = None
url = ''
form = SummarizerForm(request.form)
if request.method == "POST" and form.validate():
summary = Summarizer(form.text.data, form.algorithm.data, form.length.data)
if summary.error:
flash(summary.error)
else:
source_url = form.text.data if form.text.data.startswith(('http://', 'https://')) else ''
summary_db_entry = Summary(
summary.bullets,
summary.highlighted_text,
source_url=source_url)
db.session.add(summary_db_entry)
db.session.commit()
url_hash = summary_db_entry.url
url = os.path.join(request.url, url_for('home.summary_entry', url_hash=url_hash)[1:])
flash_errors(form)
return render_template(
'home/index.html',
form=form,
summary=summary,
url=url
)
#home.route('/s/<url_hash>')
def summary_entry(url_hash):
summary = Summary.query.filter_by(url=url_hash).first_or_404()
source_url = summary.source_url
return render_template(
'home/summary.html',
summary=summary,
source_url=source_url
)
#home.route('/about')
#home.route('/about/')
def about():
return render_template('home/about.html')
And the init.py out of the package
from .views.home import home
I get the following error on init.py which is out of the package.
Traceback (most recent call last):
File "/Users/johnsriskandarajah/Documents/summarizer-flask-app-master/tldrapp/__init__.py", line 35, in <module>
from .views.home import home
ValueError: Attempted relative import in non-package
How can this error be fixed? I tried out most of the solutions online but couldn't find any luck.
Full project structure
Related
I've got a blueprint file /views/index.py:
from flask import Blueprint, render_template
index = Blueprint('index', __name__)
def auth():
return "dog"
#index.route('/')
def index_view():
return render_template(
'index.html', user=auth())
This is initialized fine from /main.py:
from flask import Flask
from views.index import index
from views.login import login
app = Flask(__name__)
app.register_blueprint(index)
How can I mock the auth() function in my blueprint to return an override like "cat"?
Use the following /tests/test_root.py:
import sys
from pathlib import Path
sys.path.append(str(Path('.').absolute().parent))
from main import app
def test_index_route(mocker):
mocker.patch("views.index.auth", return_value="cat")
response = app.test_client().get('/')
assert response.status_code == 200
assert b"cat" in response.data
assert not b"dog" in response.data
Navigate into the /tests/ dir, run pytest and this test will pass.
I started learning flask a few days ago from the e-book flask framework cookbook.
I am confused about the following error.
File "run.py", line 1, in <module>
from my_app import app
File "/home/kenosis/flask_app/my_app/__init__.py", line 2, in <module>
from my_app.product.views import product_blueprint
File "/home/kenosis/flask_app/my_app/product/views.py", line 10
def home():
^
IndentationError: unexpected indent
This is my views.py
from werkzeug import abort
from flask import render_template
from flask import Blueprint
from my_app.product.models import PRODUCTS
product_blueprint = Blueprint('product', __name__)
#product_blueprint.route('/')
#product_blueprint.route('/home')
def home():
return render_template('home.html', products=PRODUCTS)
#product_blueprint.route('/product/<key>')
def product(key):
product = PRODUCTS.get(key)
if not product:
abort(404)
return render_template('product.html', product=PRODUCTS)
and then this is my init
from flask import Flask
from my_app.product.views import product_blueprint
app = Flask(__name__)
app.register_blueprint(product_blueprint)
product_blueprint = Blueprint('main', __name__, template_folder='templates')
What am I doing wrong?
Indentation is very important in Python. Do not indent after the decorator
from flask import render_template, abort
from flask import Blueprint
from my_app.product.models import PRODUCTS
product_blueprint = Blueprint('product', __name__)
#product_blueprint.route('/')
#product_blueprint.route('/home')
def home():
return render_template('home.html', products=PRODUCTS)
#product_blueprint.route('/product/<key>')
def product(key):
product = PRODUCTS.get(key)
if not product:
abort(404)
return render_template('product.html', product=PRODUCTS)
I am entering an url to process a file and return me an api with an output example: 12.334.198.190:5000/home/files/xyx.pdf and in my linux vm the address of the file is /home/files/xyz.pdf so the error is 'No such file or directory: home/files/xyz.pdf'. I think the '/' before home is not being picked up and thus the error. Any idea how to fix this?
Adding code for reference:
import ectd
from ectd import convert
from flask import Flask, request
from flask_restful import Resource, Api
#from flask.views import MethodView
app = Flask(__name__)
api = Api(app)
class ectdtext(Resource):
def get(self, result):
return {'data': ectd.convert(result)}
#api.add_resource(ectdtext, '/ectd/<result>')
#categorie
#app.route('/', defaults={'path': ''})
#app.route('/<path:path>')
def get_dir(path):
categories = convert(path)
return categories
##app.route('/get_dir/<path>')
#def get_dir(path):
# return path
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000)
I am attempting to run pyad in a flask app.
from flask import Flask, render_template, flash, request
from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
from pyad import *
import folder_module
# App config.
DEBUG = True
app = Flask(__name__)
app.config.from_object(__name__)
app.config['SECRET_KEY'] = 'SECRETKEY'
class ReusableForm(Form):
uid1 = TextField('UID1:', validators=[validators.required()])
uid2 = TextField('UID2:', validators=[validators.required()])
folder = TextField('Folder Name:', validators=[validators.required()])
#app.route("/", methods=['GET', 'POST'])
def fold():
form = ReusableForm(request.form)
print(form.errors)
if request.method == 'POST':
uid1 = request.form['uid1']
uid2 = request.form['uid2']
foldername = request.form['folder']
if form.validate():
ou = pyad.adcontainer.ADContainer.from_dn("ou=Groups, dc=ad, dc=test, dc=com")
flash(ou)
else:
flash('All the form fields are required. ')
return render_template('folder.html', form=form)
if __name__ == "__main__":
app.run()
I am hoping that I can call into pyad to create a security group. But even running a query on the ad container (ou via dn in this case) gives me a win32 error. The main fail error is resulted from that line and gives the following win32types error.
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147221020), None)
I have tried running this in 32bit and 64 bit python, as well as with AD.setdefault auth.
Is there anything else I can do?
pywintypes.com error when running pyad.adgroup on flask
It looks like someone else has a similar question
I solve this error using pythoncom library inside any route.
from flask import Flask, render_template, request
import pythoncom
import pyad
#app.route('/')
def index():
pythoncom.CoInitialize()
I'm having problems integrating Celery in my Flask application.
This is the repo https://github.com/theobouwman/community-python.
I start my app by running app.py which imports my app (where blueprints and config are added) and Celery.
In /tasks/add.py I have a sample task and where I import the Celery object again for the #celery.task decorator.
Till that point everything works fine. I can run my Flask application and run the Celery worker.
But when I try to trigger a task from within a controller in a Blueprint like here https://github.com/theobouwman/community-python/blob/master/auth/controllers/RegistrationController.py#L38 it says that it cannot import it, which it a logic reaction.
Traceback (most recent call last):
File "app.py", line 2, in <module>
from flask_app import app
File "/development/projects/python/Community/flask_app.py", line 4, in <module>
from auth.routes import auth
File "/development/projects/python/Community/auth/routes.py", line 3, in <module>
from .controllers import RegistrationController, AuthenticationController, LogoutController
File "/development/projects/python/Community/auth/controllers/RegistrationController.py", line 10, in <module>
from tasks.add import add
File "/development/projects/python/Community/tasks/add.py", line 1, in <module>
from app import celery
File "/development/projects/python/Community/app.py", line 2, in <module>
from flask_app import app
ImportError: cannot import name 'app'
I don't know how to fix this import cycle and that's the reason for this question. I googled for like 3 hours but couldn't find a solution.
I hope someone here could help me.
And is there a Flask Slack or Gitter in the air?
Thanks in advance.
Change your import in RegistrationController.py to a local one to solve the circular import:
from ..blueprint import auth
from models import User
from flask import redirect, url_for, request, render_template, flash
import bcrypt
from ..forms.register import SimpleRegistrationForm
"""
Error in python3.6 app.py
Says cyclus import error
"""
# Comment out the line below
# from tasks.add import add
#auth.route('/register', methods=['GET', 'POST'])
def register():
form = SimpleRegistrationForm(request.form)
if request.method == 'POST' and form.validate():
fname = request.form['fname']
sname = request.form['sname']
email = request.form['email']
password = request.form['password']
hashed = bcrypt.hashpw(password.encode('utf-8 '), bcrypt.gensalt())
user = User.select().where(User.email == email)
if user.exists():
flash('Er bestaat al een account met dit email adres')
return redirect(url_for('auth.register'))
user = User(fname=fname, sname=sname, email=email, password=hashed)
user.save()
flash('Uw account is aangemaakt. Kijk in uw mailbox voor de activatie link')
return redirect(url_for('auth.register'))
return render_template('pages/register.html', form=form)
#auth.route('/register/test')
def register_test():
# local import avoids the cycle
from tasks.add import add
add.delay()
# hashed = bcrypt.hashpw('test'.encode('utf-8 '), bcrypt.gensalt())
# user = User(
# fname='Theo',
# sname='Bouwman',
# email='theobouwman98#gmail.com',
# password=hashed
# )
# user.save()
return redirect(url_for('auth.login'))