reznov11 reznov11 - 3 months ago 22
Apache Configuration Question

Why am getting Bad Request in login page and search form, FLASK?

If i want to log into my control panel am getting 400 bad request error that says:

Bad Request

The browser (or proxy) sent a request that this server could not understand.


I have also a search form , if i want to search for something through the database, am getting the same error .

The site is working on
Apache
webserver, what really interesting is that, if a ran the application using the
python manage.py runserver
command, the error won't show any more just in Apache the error showing up .

Here is how the code looks like in my views.py:

@app.route('/login/', methods=('GET', 'POST'))

@auth.login_required

def login():



if session.get('username') or session.get('is_author') == True:

flash("Already logged in .")

return redirect(url_for('index'))



form = LoginForm()

error = None



if request.method == 'GET' and request.args.get('next'):

session['next'] = request.args.get('next')



if form.validate_on_submit():

user = User.query.filter_by(

username = form.username.data

).first()



if user:

if bcrypt.hashpw(form.password.data, user.password) == user.password:

session['username'] = form.username.data

session['is_author'] = user.is_author



if 'next' in session:

next = session.get('next')

session.pop('next')

return redirect(next)

else:

flash('Welcome back %s'%session['username'].upper())

return redirect(url_for('index'))



else:

error = "Incorrect username or password ."

flash(error)

else:

flash(error)

error = "Incorrect username or username ."



return render_template('auth/login.html', form=form)


Also the search code in views.py:

def replace_last(source_string, replace_what, replace_with):

head, sep, tail = source_string.rpartition(replace_what)

return head + replace_with + tail



@app.route('/search/<query>', methods=['GET','POST'])

def search_engine(query):



user = User.query.first()



try:

query = request.form['autocomplete']

r = replace_last(query, ' ', '')

posts = Post.query.filter(Post.title.like('%'+r+'%')).order_by(Post.publish_date.desc())



except TypeError:

flash('No results.')

return render_template('main/search_form.html')



context = {

"posts":posts,

"r":r,

"user":user,

"query":query

}



return render_template('main/search_form.html', **context)


Another thing to mention is that, my site is running under HTTPS , maybe this causing some problems, i really don't know !! , in fact am using Letsencrypt, in another article I've seen the people are saying that there's a certain problem when using flask and HTTPS especially when using requests like POST or GET, but i really deleted Letsencrypt from my server restarted Apache but that didn't solved the problem , am really frustrated don't know what to do.

Another thing i forgot to add, is the App.conf in /etc/apache2/site-available , maybe it help some way to know what causing the problem :

<VirtualHost *:80>
ServerName site.com
ServerAlias www.site.com
WSGIScriptAlias / /var/www/MyApp/flaskapp.wsgi
<Directory /var/www/MyApp/siteapp/>
Order allow,deny
Allow from all
</Directory>
Alias /static /var/www/MyApp/siteapp/static
<Directory /var/www/MyApp/siteapp/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
RewriteEngine on
RewriteCond %{SERVER_NAME} =www.site.com [OR]
RewriteCond %{SERVER_NAME} =site.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]
</VirtualHost>


Inside
sites-available/App.conf
i did a proxy redirection, so i ran my application using the
runserver
command, then inside App.conf i added these too lines of codes :

ProxyPass / http://0.0.0.0:5000/
ProxyPassReverse / http://0.0.0.0:5000/


So by that, the Bad Request disappeared, the wired thing now is, always i'am getting wtform error that says:

This field is required.


means its empty, practically its not, i really typing information and handling them inside my views.py as i mentioned above .

Eventually, please any help would be a millions appreciated .

Answer

I solved the problem, in case you faced this unbelievable, undebugable problem do the following:

  1. remove Apache2 with all it dependencies, so :

    sudo apt-get purge apache2 apache2-utils

  2. then follow this tutorial which is about, how to deploy your flask application on nginx webserver:

    https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uwsgi-and-nginx-on-ubuntu-16-04

That's it, I'am really truly very happy right now :) .