Related
I'm new to Flask and JS, so I'm really not sure what the problem is here.
app.py
#app.route('/email', methods=["GET", "POST"])
def email():
email_form = EmailForm(csrf_enabled=False)
return render_template("email-form.html", template_form=email_form, action='/appliance2', method='POST')
forms.py (I created that validator using the template from the wtForms docs)
class DBPresenceCheck(object):
def __init__(self, table, message="Field is invalid"):
self.table = table
self.message = message
def __call__(self, form, field):
presence = Connector().query('SELECT 1 FROM %(table)s WHERE %(col_name)s = %(data)s LIMIT 1;',
{'col_name': field.label, 'data': field.data, 'table': self.table})
if presence == 1:
raise ValidationError(self.message)
class EmailForm(FlaskForm):
title = "Enter Household Info"
subtitle = "Please enter your email address:"
email_input = StringField("email", validators=[email(),
DBPresenceCheck('Household', 'That email is already present in the database.')])
# print(email_input.data)
submit = SubmitField("Submit")
email-form.html
{% extends "base.html" %}
{% block content%}
<div class="container py-4">
<div class="p-5 mb-4 bg-light rounded-3">
<h2 class="display-5 fw-bold">{{ template_form.title }}</h2>
<p class="col-md-8 fs-4">{{ template_form.subtitle }}</p>
<form action="{{ action }}" method="{{ method }}">
<div id="main_elements">
{{ template_form['email_input']() }}
</div>
<div id="submit_element">
<br>
{{ template_form["submit"](class_="btn btn-primary") }}
</div>
</form>
</div>
</div>
{%endblock%}
I first realized something was wrong when I was testing the validation, and neither validator ever threw. I added the print statement in forms, and now, when I use flask run, I get the following error.
Traceback (most recent call last):
File "C:\Languages\Python\3.9\lib\runpy.py", line 197, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Languages\Python\3.9\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\Scripts\flask.exe\__main__.py", line 7, in <module>
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\flask\cli.py", line 1047, in main
cli.main()
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\core.py", line 1055, in main
rv = self.invoke(ctx)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\core.py", line 1657, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\core.py", line 1404, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\decorators.py", line 84, in new_func
return ctx.invoke(f, obj, *args, **kwargs)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\flask\cli.py", line 911, in run_command
raise e from None
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\flask\cli.py", line 897, in run_command
app = info.load_app()
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\flask\cli.py", line 312, in load_app
app = locate_app(import_name, None, raise_if_not_found=False)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\flask\cli.py", line 218, in locate_app
__import__(module_name)
File "C:\Users\askat\PycharmProjects\cs6400-2022-03-Team060\Phase_3\app.py", line 4, in <module>
from forms import *
File "C:\Users\askat\PycharmProjects\cs6400-2022-03-Team060\Phase_3\forms.py", line 33, in <module>
class EmailForm(AddForm):
File "C:\Users\askat\PycharmProjects\cs6400-2022-03-Team060\Phase_3\forms.py", line 37, in EmailForm
print(email_input.data)
AttributeError: 'UnboundField' object has no attribute 'data'
If the print statement is just print(email_input), then when I run it, the following output
<UnboundField(StringField, ('email',), {'validators': [<wtforms.validators.Email object at 0x0000024145A4F460>, <forms.DBPresenceCheck object at 0x0000024145A4F610>]})>
but no errors are thrown. It seems strange to me that the error is thrown before the field is even created.
In the validators list you need to pass in an instance of class Email. So you field should read:
from wtforms.validators import Email
email_input = StringField("email", validators=[Email(), ...
and don't forget to install the email package as Flask-WTF doesn't include anymore the Email in their validators.
I'm using apache and python to run my web pages. But when I try to save even a txt file generated on the fly, the file is not saved.
def save(req):
try:
fe1=req.form['fe1']
fe2=req.form['fe2']
file=open("file.txt",'w')
file.write("%s %s" %(fe1,fe2))
file.close()
except KeyError:
fe1=''
fe2=''
view="""
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method=post action="#">
<input type='text' id='fe1'></input>
<input type='text' id='fe2'></input>
<input type='submit'>
</form>
</body>
</html>
""".format(**locals())
return (view)
After I submi the form I get this:
Mod_python error: "PythonHandler mod_python.publisher"
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/mod_python/apache.py", line 399, in HandlerDispatch
result = obj(req)
File "/usr/lib64/python2.7/site-packages/mod_python/publisher.py", line 222, in handler
published = publish_object(req, object)
File "/usr/lib64/python2.7/site-packages/mod_python/publisher.py", line 446, in publish_object
return publish_object(req, util.apply_fs_data(obj, req.form, req=req))
File "/usr/lib64/python2.7/site-packages/mod_python/util.py", line 642, in apply_fs_data
return object(**args)
File "<string>", line 5, in save
IOError: [Errno 13] Permission denied: 'file.txt'
Using django. I have the following model:
class Postagem(models.Model):
id = models.AutoField(primary_key=True, editable=False)
descricao = models.CharField(max_length=50)
area = models.ForeignKey('core.Area', null=True)
user = models.ForeignKey('User')
categoria = models.CharField(max_length=50, null=True)
post = models.FileField(upload_to='posts/', null=True)
thumbnail = models.FileField(upload_to='posts/', null=True)
def __str__(self):
return self.descricao
The Following form:
class PostForm(forms.ModelForm):
categoria = forms.ChoiceField(choices=[("Video","Vídeo"),("Audio","Aúdio"),("Imagem","Imagem"),("Musica","Música")], required=True)
thumbnail = forms.FileField(required=False)
class Meta:
model = Postagem
fields = ['descricao', 'area', 'user', 'post']
View:
def profileView(request):
context = getUserContext(request)
if request.method == 'POST':
exception=None
userDict = {}
userDict["user"] = context["user"].id
if "categoria" in request.POST:
newPost = request.POST.copy()
newPost.update(userDict)
form = PostForm(newPost,request.FILES)
print("postform POST: ",newPost, " File ",request.FILES)
if form.is_valid():
print("valid")
try:
form.save()
print("saved")
return HttpResponseRedirect(reverse_lazy('accounts:profile'))
except IntegrityError as e:
print("Integrity Error")
exception=e
else:
print("PostForm error")
print(form.errors)
form.non_field_errors=form.errors
if exception is not None:
form.non_field_errors.update(exception)
context['form']=form
posts = Postagem.objects.get_queryset().order_by('id')
paginator = Paginator(posts, 12)
page = request.GET.get('page')
context["areas"] = Area.objects.all()
try:
posts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
posts = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
posts = paginator.page(paginator.num_pages)
context["posts"]=posts
return render(
request,
'accounts/profile.html',
context
)
And at last the template:
{% for post in posts %}
{% if forloop.counter0|divisibleby:4 or forloop.counter0 == 0 %}
<div id="grid-profile" class="row grid">
<div class="col-md-1"></div>
{% endif %}
{% ifnotequal post.categoria "Imagem"%}
<iframe id=post{{forloop.counter}} width="420" height="315"
src={{post.post.url}}>
</iframe>
{% else %}
<div class="col-md-2">
<button type="button" id="modal1trigger" data-toggle="modal" data-target="#modal1"><img class="img-responsive" src={{post.post.url}}></img></button>
</div>
{% endifnotequal %}
{% if forloop.counter|divisibleby:4 or forloop.counter == posts|length %}
<div class="col-md-1"></div>
</div>
{% endif %}
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if posts.has_previous %}
previous
{% endif %}
<span class="current">
Page {{ posts.number }} of {{ posts.paginator.num_pages }}.
</span>
{% if posts.has_next %}
next
{% endif %}
</span>
</div>
I cut some of the template... Anyways, I want to be able to add all kinds of posts. Songs, Videos, Images, Docs, etc. And it IS working. The posts are being added. But, I'm having a recurring error and I don't know why. That could be very dangerous so I started looking into it, but with no luck in finding an acceptable answer. The error only happens when trying to get a song or a video.
[21/Sep/2017 23:32:44] "GET /media/posts/13567830_1641362072853439_1924036772_n.mp4 HTTP/1.1" 200 1171456
Traceback (most recent call last):
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 138, in run
self.finish_response()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 180, in finish
_response
self.write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 279, in write
self._write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 453, in _write
result = self.stdout.write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 775, in write
self._sock.sendall(b)
ConnectionResetError: [WinError 10054] Foi forçado o cancelamento de uma conexão existente pelo host remoto
[21/Sep/2017 23:32:44] "GET /media/posts/13567830_1641362072853439_1924036772_n.mp4 HTTP/1.1" 500 59
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 53113)
Traceback (most recent call last):
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 138, in run
self.finish_response()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 180, in finish
_response
self.write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 279, in write
self._write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 453, in _write
result = self.stdout.write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 775, in write
self._sock.sendall(b)
ConnectionResetError: [WinError 10054] Foi forçado o cancelamento de uma conexão existente pelo host remoto
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 141, in run
self.handle_error()
File "C:\Users\eduardo\Envs\ProExC\lib\site-packages\django\core\servers\basehttp.py", line 88, in handle_erro
r
super(ServerHandler, self).handle_error()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 368, in handle
_error
self.finish_response()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 180, in finish
_response
self.write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 274, in write
self.send_headers()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 331, in send_h
eaders
if not self.origin_server or self.client_is_modern():
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 344, in client
_is_modern
return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
TypeError: 'NoneType' object is not subscriptable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 639, in process_re
quest_thread
self.finish_request(request, client_address)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 361, in finish_req
uest
self.RequestHandlerClass(request, client_address, self)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 696, in __init__
self.handle()
File "C:\Users\eduardo\Envs\ProExC\lib\site-packages\django\core\servers\basehttp.py", line 155, in handle
handler.run(self.server.get_app())
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 144, in run
self.close()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\simple_server.py", line 35, in cl
ose
self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'
----------------------------------------
[21/Sep/2017 23:32:44] "GET /media/posts/03_-_The_Mute.mp3 HTTP/1.1" 200 1179648
Traceback (most recent call last):
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 138, in run
self.finish_response()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 180, in finish
_response
self.write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 279, in write
self._write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 453, in _write
result = self.stdout.write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 775, in write
self._sock.sendall(b)
ConnectionResetError: [WinError 10054] Foi forçado o cancelamento de uma conexão existente pelo host remoto
[21/Sep/2017 23:32:44] "GET /media/posts/03_-_The_Mute.mp3 HTTP/1.1" 500 59
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 53114)
Traceback (most recent call last):
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 138, in run
self.finish_response()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 180, in finish
_response
self.write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 279, in write
self._write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 453, in _write
result = self.stdout.write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 775, in write
self._sock.sendall(b)
ConnectionResetError: [WinError 10054] Foi forçado o cancelamento de uma conexão existente pelo host remoto
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 141, in run
self.handle_error()
File "C:\Users\eduardo\Envs\ProExC\lib\site-packages\django\core\servers\basehttp.py", line 88, in handle_erro
r
super(ServerHandler, self).handle_error()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 368, in handle
_error
self.finish_response()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 180, in finish
_response
self.write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 274, in write
self.send_headers()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 331, in send_h
eaders
if not self.origin_server or self.client_is_modern():
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 344, in client
_is_modern
return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
TypeError: 'NoneType' object is not subscriptable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 639, in process_re
quest_thread
self.finish_request(request, client_address)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 361, in finish_req
uest
self.RequestHandlerClass(request, client_address, self)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 696, in __init__
self.handle()
File "C:\Users\eduardo\Envs\ProExC\lib\site-packages\django\core\servers\basehttp.py", line 155, in handle
handler.run(self.server.get_app())
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 144, in run
self.close()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\simple_server.py", line 35, in cl
ose
self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'
---------------------------------------
Edit:
Using Django 1.11.3,
Windows 10,
Tested with Opera and Chrome,
Running server using gulp
**Edit 2: **
Hey, the error ONLY HAPPENS if there is a iframe tag in the html!!
It appears that its a python error:
Django ticket: https://code.djangoproject.com/ticket/26995
Python ticket: https://bugs.python.org/issue14574
Didn't managed to solve just yet, if I can I will edit this answer explaining in detail how to solve it.
Edit
It seems to be a error on chrome. It didn't come to me, 'cause I was using Opera, but opera uses chromium as well. In internet explorer the error didn't show.
https://code.djangoproject.com/ticket/21227#no1
This is the bug tracker
the first error
self.environ['SERVER_PROTOCOL'].upper() is failing because self.environ['SERVER_PROTOCOL'] is None, and you can't do None.upper() you can only do .upper() on strings (as far as i'm aware).
the second error
self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'
This is failing because you self.status is None and you can't do None.split(), again this should be a string.
So it looks like some of the required values for these classes aren't being initialised or passed through.
It looks like the issue is with Django.core and WSGIref, so either the configuration isn't correct or perhaps there's an issue with the version you have installed?
Which version of Django are you running?
Also are you running the server from ./manage.py runserver ?
[update 2017-09-28]
There's a couple of things I've modified, to start with I'm not copying the request.POST to a new dict, before passing it, this could be the cause of some of the values disappearing when trying to process a post.
I'm also passing user as a kwarg to your form, rather than trying to inject it into the copied POST.
mostly I've just updated some of the code to be a little easier to read, let's see how that goes.
# forms.py
class PostForm(forms.ModelForm):
categoria = forms.ChoiceField(choices=[("Video","Vídeo"),("Audio","Aúdio"),("Imagem","Imagem"),("Musica","Música")], required=True)
thumbnail = forms.FileField(required=False)
class Meta:
model = Postagem
fields = ['descricao', 'area', 'user', 'post']
def __init__(self, *args, **kwargs): # handle user kwarg
if 'user' in kwargs.keys():
self.user = kwargs.pop('user')
super(PostForm, self).__init__(*args, **kwargs)
# views.py
def profileView(request):
form = None
if request.method == 'POST':
exception=None
if "categoria" in request.POST:
if request.user:
form = PostForm(request.POST,request.FILES, user=request.user) # pass user as a kwarg
print("postform POST: ",newPost, " File ",request.FILES)
if form.is_valid():
print("valid")
try:
form.save()
print("saved")
return HttpResponseRedirect(reverse_lazy('accounts:profile'))
except IntegrityError as e:
print("Integrity Error")
exception=e
else:
print("PostForm error")
print(form.errors)
#form has been indented as previously it would have been called before being initialised
form.non_field_errors=form.errors
if exception is not None:
form.non_field_errors.update(exception)
posts = Postagem.objects.get_queryset().order_by('id')
paginator = Paginator(posts, 12)
page = None
if request.GET:
page = request.GET.get('page')
areas = Area.objects.all()
try:
posts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
posts = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
posts = paginator.page(paginator.num_pages)
#return values
return render(
request,
'accounts/profile.html',
{
'form': form,
'areas': areas,
'posts': posts,
}
)
Are you using PostgreSQL? It could be caused by a code page error.
C:\>psql -U postgres
psql (10.5)
WARNING: Console code page (850) differs from Windows code page (1252)
8-bit characters might not work correctly. See psql reference
page "Notes for Windows users" for details.
Type "help" for help.
postgres=#
Trying setting the code page before you start Django.
cmd.exe /c chcp 1252
I am creating a simple app in Python 3.5.2 that authenticates users via Active Directory and applies additional rules based on a user's group membership. The app can successfully authenticate users using the win32security package, and tries to obtain group membership info using pyad.
My problem: I get a pywintypes.com_error message when running the code on my Flask app, preventing me from getting group membership info.
When I run the backend code separately on an iPython console, it works fine. I am able to query group membership. However, when it is part of a Flask app, an error pops out. I have isolated the problem to this part of the code (DN information masked):
group = adgroup.ADGroup.from_dn('CN=someCN,OU=someOU1,OU=someOU2,
DC=test,DC=domain,DC=com,DC=somecountry')
group_members = sum([member.get_attribute("sAMAccountName")
for member in group.get_members()],[])
Has anyone encountered this before? I cannot think of why the code won't run in Flask (though I have just started learning Flask) but it will run in the console.
Code Reference:
I have 3 Python files for my Flask app and an html file in the templates folder.
run.py
from app import app
import os
app.secret_key = os.urandom(16)
app.run(debug=True)
init.py
from flask import Flask
app = Flask(__name__)
from app import views
views.py
from app import app
from flask import Flask, flash, render_template, request, session
import win32security as win32
from pyad import adgroup
#app.route("/")
def home():
if not session.get("logged_in"):
return render_template("login.html")
else:
return "You are currently logged in."
#app.route("/login", methods=["GET","POST"])
def login():
#initialize variables
username = request.form["username"]
password = request.form["password"]
DOMAIN = "test.domain.com.somecountry"
error = None
group = adgroup.ADGroup.from_dn('CN=someCN,OU=someOU1,OU=someOU2,DC=test,DC=domain,DC=com,DC=somecountry')
group_members = sum([member.get_attribute("sAMAccountName") for member in group.get_members()],[])
if username in group_members:
try:
token = win32.LogonUser(username, DOMAIN, password,
win32.LOGON32_LOGON_NETWORK,
win32.LOGON32_PROVIDER_DEFAULT)
is_auth = bool(token)
if is_auth:
session["logged_in"] = True
except:
error = "Incorrect credentials. Please try again."
else:
error = "You are not permitted to access this."
return render_template("login.html", error=error)
login.html
<!doctype html>
<title>Login Test</title>
{% block body %}
{% if session["logged_in"] %}
<p>You are currently logged in.</p>
{% else %}
<form action="/login" method="POST">
<input type="username" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Log In">
</form>
<li>{{error}}</li>
{% endif %}
{% endblock %}
This is the error traceback:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1567, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\user\Documents\test\app\views.py", line 23, in login
group = adgroup.ADGroup.from_dn('CN=someCN,OU=someOU1,OU=someOU2,DC=test,DC=domain,DC=com,DC=somecountry')
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\pyad\adobject.py", line 131, in from_dn
return cls(distinguished_name, None, options)
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\pyad\adobject.py", line 88, in __init__
self.__set_adsi_obj()
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\pyad\adobject.py", line 76, in __set_adsi_obj
self._ldap_adsi_obj = self.adsi_provider.getObject('', self.__ads_path)
File "<COMObject ADsNameSpaces>", line 2, in getObject
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147221020), None)
I was able to mitigate this error by running my same code in a python2 32bit environment.
Not sure if this is an option, but worth a shot.
I'm trying to modify already existing code, simply add form to add photos.
python:
#route('/photos/add')
#jinja_view('add.html')
#post('/photos/add')
def upload_func():
upload = request.files.get('pic')
name, ext = os.path.splitext(upload.filename)
if ext not in ('.png', '.jpg', '.jpeg'):
return "ext is not allowed"
save_path = "/src/photo_gallery/photos"
upload.save(save_path)
return "photo is saved"
HTML:
<form action="/photos/add" method="post">
<div align="center">
<label>Picture</label>
<input type="file" name="pic" required>
</div>
<div>
<label>Info</label>
<input type="text" name="text">
</div>
<div>
<input type="submit" value="add">
</div>
</form>
server log:
Traceback (most recent call last):
File "/home/empty/python/bottle/lib/python3.5/site-packages/bottle.py", line 862, in _handle
return route.call(**args)
File "/home/empty/python/bottle/lib/python3.5/site-packages/bottle.py", line 1740, in wrapper
rv = callback(*a, **ka)
File "/home/empty/python/bottle/lib/python3.5/site-packages/bottle.py", line 3635, in wrapper
result = func(*args, **kwargs)
File "/home/empty/python/bottle/src/photo_gallery/app.py", line 50, in upload_func
name, ext = os.path.splitext(upload.filename)
AttributeError: 'NoneType' object has no attribute 'filename'
127.0.0.1 - - [22/Dec/2016 23:20:42] "GET /photos/add HTTP/1.1" 500 751
You have linked the url path /photos/add to the callback function upload_func. It looks like you want to support two request types (GET and POST), then function decorators should look like this:
#route('/photos/add', method=['GET', 'POST'])
#jinja_view('add.html')
def upload_func():
# ...
Take a look at:
https://bottlepy.org/docs/dev/tutorial.html#request-routing
https://bottlepy.org/docs/dev/api.html#bottle.Bottle.route
Please also note that the code should not be written like this - too complex