Problem z uruchomieniem web aplikacji python flask

Odpowiedz Nowy wątek
2019-06-07 18:59
0
File "/usr/home/MOOOJUSER/.virtualenvs/web_app/lib/python3.6/site-packages/MySQLdb/__init__.py", line 18, in <module>
    from . import _mysql
ImportError: cannot import name '_mysql

Czy ktoś miał podobny problem na serwerze mydevil? Czy muszę doinstalować jakieś dodatkowe paczki? Wiem, że nie może zimportować tego pliku. MySQLdb przerzuciłem bezpośrednio z komputera na serwer, nie instalowałem tego przez konsolę. Jak wpisywałem "pip install MySQL-python" w konsoli to wyskakiwał taki problem

Collecting MySQL-python
  Using cached https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip
    ERROR: Complete output from command python setup.py egg_info:
    ERROR: Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-y23kdnjk/MySQL-python/setup.py", line 13, in <module>
        from setup_posix import get_config
      File "/tmp/pip-install-y23kdnjk/MySQL-python/setup_posix.py", line 2, in <module>
        from ConfigParser import SafeConfigParser
    ModuleNotFoundError: No module named 'ConfigParser'
    ----------------------------------------
ERROR: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-y23kdnjk/MySQL-python/
edytowany 2x, ostatnio: Lucky Bastardo, 2019-06-07 19:05

Pozostało 580 znaków

2019-06-08 13:58
0

1/ Nie kopiuj .virtualenva, tylko twórz nowego, przez virtualenv a potem instaluj zaleznosci z requirements.txt
2/ MySQL-python jest dla Pythona 2, można to poznać po tym, że szuka Tobie ConfigParsera (który jest w dwójce).
3/ Użyj pip install mysqlclient

Pozostało 580 znaków

2019-06-10 12:15
0
jackweb napisał(a):

1/ Nie kopiuj .virtualenva, tylko twórz nowego, przez virtualenv a potem instaluj zaleznosci z requirements.txt
2/ MySQL-python jest dla Pythona 2, można to poznać po tym, że szuka Tobie ConfigParsera (który jest w dwójce).
3/ Użyj pip install mysqlclient

Dzięki za odpowiedź. Teraz mam problem tego typu, że po "udanej" rejestracji (tzn. użytkownik zapisuje się w bazie) nie przenosi mnie na stronę logowania, tylko wyskakuje Internal Server Error.

from flask import Flask, render_template, flash, redirect, request, url_for, session, logging
#from data import Articles
from flask_mysqldb import MySQL
from wtforms import Form, StringField, TextAreaField, PasswordField, validators
from passlib.hash import sha256_crypt
from functools import wraps
#from inflection import parameterize
#import MySQLdb

app = Flask(__name__)

#Config Mysql
app.config['MYSQL_HOST'] = '#####'
app.config['MYSQL_USER'] = '######'
app.config['MYSQL_PASSWORD'] = '######'
app.config['MYSQL_DB'] = '######'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'

#init mysql
mysql = MySQL(app)

#Articles = Articles()

#Index
@app.route('/')
def index():
    return render_template('index.html')

#About
@app.route('/about')
def about():
    return render_template('layouts/about.html')

#Articles
@app.route('/articles')
def articles():
    # Create cursor
    cur = mysql.connection.cursor()

    # Get articles
    result = cur.execute("SELECT * FROM articles")

    articles = cur.fetchall()

    if result > 0:
        return render_template('articles.html', articles=articles)

    else:
        msg = 'Nie ma artykułów'
        return render_template('articles.html', msg=msg)
    # Close connection
    cur.close()

#Single article
@app.route('/article/<string:id>/')
def article(id):
    # Create cursor
    cur = mysql.connection.cursor()

    # Get article
    result = cur.execute("SELECT * FROM articles WHERE id = %s", [id])

    article = cur.fetchone()

    return render_template('article.html', article=article)

#Register form class
class RegisterForm(Form):
    name = StringField('Name', [validators.Length(min=1, max=50)])
    username = StringField('Username', [validators.Length(min=4, max=25)])
    password = PasswordField('Password', [
        validators.DataRequired(),
        validators.EqualTo('confirm', message='Hasła nie są takie same')
    ])
    confirm = PasswordField('Confirm Password')

#User Register
@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm(request.form)
    if request.method == 'POST' and form.validate():
        name = form.name.data
        username = form.username.data
        password = sha256_crypt.encrypt(str(form.password.data))

        #Create cursor
        cur = mysql.connection.cursor()

        #Execute query
        cur.execute("INSERT INTO users(name, username, password) VALUES(%s, %s, %s)", (name, username, password))

        #Commit to DB
        mysql.connection.commit()

        # Close connection
        cur.close()

        flash('Zostałeś zarejestrowany, możesz się zalogować', 'success')

        return redirect(url_for('login'))
    return render_template('register.html', form=form)

#User login
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        # Get Form Fields
        username = request.form['username']
        password_candidate = request.form['password']

        # Create cursor
        cur = mysql.connection.cursor()

        #Get user by username
        result = cur.execute("SELECT * FROM users WHERE username = %s", [username])

        if result > 0:
            # Get stored hash
            data = cur.fetchone()
            password = data['password']

            #Compare Passwords
            if sha256_crypt.verify(password_candidate, password):
                #Passed password
                session['logged_in'] = True
                session['username'] = username

                flash('Zostałeś zalogowany', 'success')
                return redirect(url_for('dashboard'))
            else:
                error = 'Invalid Password'
                return render_template('login.html', error = error)
            #Close connection
            cur.close()

        else:
            error = 'Username not found'
            return render_template('login.html', error = error)

    return render_template('login.html')

#Check if user logged in
def is_logged_in(f):
    @wraps(f)
    def wrap(*args, **kwargs):
        if 'logged_in' in session:
            return f(*args, **kwargs)
        else:
            flash('Nieautoryzowany dostęp! Proszę się zalogować', 'danger')
            return redirect(url_for('login'))
    return wrap

#Logout
@app.route('/logout')
def logout():
    session.clear()
    flash('Zostałeś wylogowany', 'success')
    return redirect(url_for('login'))

#Dashboard
@app.route('/dashboard')
@is_logged_in
def dashboard():
    #Create cursor
    cur = mysql.connection.cursor()

    #Get articles
    result = cur.execute("SELECT * FROM articles")

    articles = cur.fetchall()

    if result > 0:
        return  render_template('dashboard.html', articles=articles)

    else:
        msg = 'Nie ma artykułów'
        return  render_template('dashboard.html', msg=msg)
    #Close connection
    cur.close()

#Article form class
class ArticleForm(Form):
    title = StringField('Title', [validators.Length(min=1, max=100)])
    body = TextAreaField('Body')

#Add article
@app.route('/add_article', methods=['GET', 'POST'])
@is_logged_in
def add_article():
    form = ArticleForm(request.form)
    if request.method == 'POST' and form.validate():
        title = form.title.data
        body = form.body.data

        #Create cursor
        cur = mysql.connection.cursor()

        #Execute
        cur.execute("INSERT INTO articles(title, body, author) VALUES(%s, %s, %s)", (title, body, session['username']))

        #Commit to DB
        mysql.connection.commit()

        #Close connection
        cur.close()

        flash('Artykuł stworzony', 'success')

        return redirect(url_for('dashboard'))

    return render_template('add_article.html', form=form)

#Edit article
@app.route('/edit_article/<string:id>', methods=['GET', 'POST'])
@is_logged_in
def edit_article(id):
    #Create cursor
    cur = mysql.connection.cursor()

    #Get article by id
    result = cur.execute("SELECT * FROM articles WHERE id = %s", [id])

    article = cur.fetchone()

    #Get Form
    form = ArticleForm(request.form)

    #Populate article form fields
    form.title.data = article['title']
    form.body.data = article['body']

    if request.method == 'POST' and form.validate():
        title = request.form['title']
        body = request.form['body']

        #Create cursor
        cur = mysql.connection.cursor()

        #Execute
        cur.execute("UPDATE articles SET title=%s, body=%s WHERE id=%s",(title, body, id))

        #Commit to DB
        mysql.connection.commit()

        #Close connection
        cur.close()

        flash('Artykuł zauktualizowany', 'success')

        return redirect(url_for('dashboard'))

    return render_template('edit_article.html', form=form)

#Delete article
@app.route('/delete_article/<string:id>', methods=['POST'])
@is_logged_in
def delete_article(id):

    #create cursor
    cur = mysql.connection.cursor()

    #Execute
    cur.execute("DELETE FROM articles WHERE id = %s", [id])

    # Commit to DB
    mysql.connection.commit()

    # Close connection
    cur.close()

    flash('Artykuł usunięty', 'success')

    return redirect(url_for('dashboard'))

if __name__ == '__main__':
    app.secret_key='kluczsekretny123'
    app.run(debug=True)
a możesz wkleić cały traceback z konsoli, co ci konkretnie printuje? jaki błąd i tak dalej? - grski 2019-06-11 11:42

Pozostało 580 znaków

2019-06-11 13:12
0
App 74275 output: [ pid=74275, time=2019-06-10 11:50:20,340 ]: Exception on /register [POST]
App 74275 output: Traceback (most recent call last):
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 2311, in wsgi_app
App 74275 output:     response = self.full_dispatch_request()
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 1834, in full_dispatch_request
App 74275 output:     rv = self.handle_user_exception(e)
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 1737, in handle_user_exception
App 74275 output:     reraise(exc_type, exc_value, tb)
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/_compat.py", line 36, in reraise
App 74275 output:     raise value
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 1832, in full_dispatch_request
App 74275 output:     rv = self.dispatch_request()
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 1818, in dispatch_request
App 74275 output:     return self.view_functions[rule.endpoint](**req.view_args)
App 74275 output:   File "/usr/home/mojlogin/domains/nowaaplikacjaflask.ct8.pl/public_python/appi.py", line 100, in register
App 74275 output:     flash('Zosta³e¶ zarejestrowany, mo¿esz siê zalogowaæ', 'success')
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/helpers.py", line 410, in flash
App 74275 output:     session['_flashes'] = flashes
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/werkzeug/local.py", line 351, in __setitem__
App 74275 output:     self._get_current_object()[key] = value
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/sessions.py", line 101, in _fail
App 74275 output:     raise RuntimeError('The session is unavailable because no secret '
App 74275 output: RuntimeError: The session is unavailable because no secret key was set.  Set the secret_key on the application to something unique and secret.
App 74275 output: [ pid=74275, time=2019-06-10 12:03:02,757 ]: Exception on /register [POST]
App 74275 output: Traceback (most recent call last):
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 2311, in wsgi_app
App 74275 output:     response = self.full_dispatch_request()
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 1834, in full_dispatch_request
App 74275 output:     rv = self.handle_user_exception(e)
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 1737, in handle_user_exception
App 74275 output:     reraise(exc_type, exc_value, tb)
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/_compat.py", line 36, in reraise
App 74275 output:     raise value
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 1832, in full_dispatch_request
App 74275 output:     rv = self.dispatch_request()
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 1818, in dispatch_request
App 74275 output:     return self.view_functions[rule.endpoint](**req.view_args)
App 74275 output:   File "/usr/home/mojlogin/domains/nowaaplikacjaflask.ct8.pl/public_python/appi.py", line 100, in register
App 74275 output:     flash('Zosta³e¶ zarejestrowany, mo¿esz siê zalogowaæ', 'success')
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/helpers.py", line 410, in flash
App 74275 output:     session['_flashes'] = flashes
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/werkzeug/local.py", line 351, in __setitem__
App 74275 output:     self._get_current_object()[key] = value
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/sessions.py", line 101, in _fail
App 74275 output:     raise RuntimeError('The session is unavailable because no secret '
App 74275 output: RuntimeError: The session is unavailable because no secret key was set.  Set the secret_key on the application to something unique and secret.
App 74275 output: 
App 74275 output: [ pid=74275, time=2019-06-10 12:05:01,753 ]: Exception on /register [POST]
App 74275 output: Traceback (most recent call last):
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 2311, in wsgi_app
App 74275 output:     response = self.full_dispatch_request()
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 1834, in full_dispatch_request
App 74275 output:     rv = self.handle_user_exception(e)
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 1737, in handle_user_exception
App 74275 output:     reraise(exc_type, exc_value, tb)
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/_compat.py", line 36, in reraise
App 74275 output:     raise value
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 1832, in full_dispatch_request
App 74275 output:     rv = self.dispatch_request()
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 1818, in dispatch_request
App 74275 output:     return self.view_functions[rule.endpoint](**req.view_args)
App 74275 output:   File "/usr/home/mojlogin/domains/nowaaplikacjaflask.ct8.pl/public_python/appi.py", line 100, in register
App 74275 output:     flash('Zosta³e¶ zarejestrowany, mo¿esz siê zalogowaæ', 'success')
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/helpers.py", line 410, in flash
App 74275 output:     session['_flashes'] = flashes
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/werkzeug/local.py", line 351, in __setitem__
App 74275 output:     self._get_current_object()[key] = value
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/sessions.py", line 101, in _fail
App 74275 output:     raise RuntimeError('The session is unavailable because no secret '
App 74275 output: RuntimeError: The session is unavailable because no secret key was set.  Set the secret_key on the application to something unique and secret.
App 74275 output: [ pid=74275, time=2019-06-10 12:09:49,868 ]: Exception on /register [POST]
App 74275 output: Traceback (most recent call last):
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 2311, in wsgi_app
App 74275 output:     response = self.full_dispatch_request()
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 1834, in full_dispatch_request
App 74275 output:     rv = self.handle_user_exception(e)
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 1737, in handle_user_exception
App 74275 output:     reraise(exc_type, exc_value, tb)
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/_compat.py", line 36, in reraise
App 74275 output:     raise value
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 1832, in full_dispatch_request
App 74275 output:     rv = self.dispatch_request()
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 1818, in dispatch_request
App 74275 output:     return self.view_functions[rule.endpoint](**req.view_args)
App 74275 output:   File "/usr/home/mojlogin/domains/nowaaplikacjaflask.ct8.pl/public_python/appi.py", line 100, in register
App 74275 output:     flash('Zosta³e¶ zarejestrowany, mo¿esz siê zalogowaæ', 'success')
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/helpers.py", line 410, in flash
App 74275 output:     session['_flashes'] = flashes
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/werkzeug/local.py", line 351, in __setitem__
App 74275 output:     self._get_current_object()[key] = value
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/sessions.py", line 101, in _fail
App 74275 output:     raise RuntimeError('The session is unavailable because no secret '
App 74275 output: RuntimeError: The session is unavailable because no secret key was set.  Set the secret_key on the application to something unique and secret.
App 74275 output: [ pid=74275, time=2019-06-11 13:02:04,555 ]: Exception on /register [POST]
App 74275 output: Traceback (most recent call last):
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 2311, in wsgi_app
App 74275 output:     response = self.full_dispatch_request()
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 1834, in full_dispatch_request
App 74275 output:     rv = self.handle_user_exception(e)
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 1737, in handle_user_exception
App 74275 output:     reraise(exc_type, exc_value, tb)
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/_compat.py", line 36, in reraise
App 74275 output:     raise value
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 1832, in full_dispatch_request
App 74275 output:     rv = self.dispatch_request()
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/app.py", line 1818, in dispatch_request
App 74275 output:     return self.view_functions[rule.endpoint](**req.view_args)
App 74275 output:   File "/usr/home/mojlogin/domains/nowaaplikacjaflask.ct8.pl/public_python/appi.py", line 100, in register
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/helpers.py", line 410, in flash
App 74275 output:     session['_flashes'] = flashes
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/werkzeug/local.py", line 351, in __setitem__
App 74275 output:     self._get_current_object()[key] = value
App 74275 output:   File "/usr/home/mojlogin/.virtualenvs/nowa_aplikacja_flask/lib/python3.5/site-packages/flask/sessions.py", line 101, in _fail
App 74275 output:     raise RuntimeError('The session is unavailable because no secret '
App 74275 output: RuntimeError: The session is unavailable because no secret key was set.  Set the secret_key on the application to something unique and secret.

Pozostało 580 znaków

Odpowiedz
Liczba odpowiedzi na stronę

1 użytkowników online, w tym zalogowanych: 0, gości: 1, botów: 0