Need some more detailed tutorial on flask tryton

Hey guys
Can anyone teach me(or point me to a site) on how to do flask tryton in more detail than what is on the py website?

1 Like

I think there is no such documentation (or at least we are not aware of it).

If you want to learn how to use flask-tryton I will recomend learing first the flask basics and also the tryton basics. Once you are familiar with both concepts using flask-tryton is easier.

What basics do i need to learn in tryton?

You need to know how the tryton ORM works as normally flask tryton interact with tryton models to use its data.

Once you have this it depends on the application but you will need to know how the modules you have activated in the database are designed in order to follow it’s usages from flask tryton.

Here is an example which uses flask-tryton and web_user for authentication:

Click to show the example
from flask import Flask
from flask_tryton import Tryton
from flask.ext.babel import Babel

app = Flask(__name__)      
babel = Babel(app)                                                             
app.config['TRYTON_DATABASE'] = os.environ.get('DB_NAME', 'tryton') 
tryton = Tryton(app, configure_jinja=True)

WebUser = tryton.pool.get('web.user')                                          
Session = tryton.pool.get('web.user.session')                                                                                


def login_required(func):                                                      
    @wraps(func)                                                               
    def wrapper(*args, **kwargs):                                              
        session_key = None                                                     
        if 'session_key' in session:                                           
            session_key = session['session_key']                               
        user = Session.get_user(session_key)                                   
        if not user:                                                           
            return redirect(url_for('login', next=request.path))               
        return func(*args, **kwargs)                                           
    return wrapper                                                             


class LoginForm(FlaskForm):                                                    
    email = StringField('Correo Electrónico',                                  
        validators=[DataRequired()],                                           
        render_kw={'placeholder': 'Correo Electrónico'})                       
    password = PasswordField('Contraseña',                                     
        validators=[DataRequired()],                                           
        render_kw={'placeholder': 'Contraseña'})                               


@app.route('/login', methods=['GET', 'POST'])                                  
@tryton.transaction()                                                          
def login():                                                                   
    form = LoginForm()                                                         
    if request.method == 'POST' and form.validate_on_submit():                 
        user = WebUser.authenticate(form.email.data, form.password.data)       
        if user:                                                               
            session['session_key'] = WebUser.new_session(user)                 
            flash('Ahora estas identificado.', 'success')                      
            return redirect(request.form.get('next', url_for('index')))        
        flash('Email o contraseña incorrectos.', 'error')                      
    return render_template(                                                    
        'login.html',                                                          
        form=form,                                                             
        next=request.args.get('next'))                                         


@app.route('/logout')                                                          
@tryton.transaction(readonly=False)                                            
@login_required                                                                
def logout():                                                                  
    if session['session_key']:                                                 
        Session.delete(Session.search(                                         
                ('key', '=', session['session_key']),                          
                ))                                                             
        session.pop('session_key', None)                                       
        flash("Se ha desconectado tu sessión", 'success')                      
    return redirect(url_for('index')) 


@app.route('/')                                                                
@tryton.transaction()                                                          
def index():                                                                   
    return render_template('index.html')    

                                                          
@app.route('/my-account')                                                       
@tryton.transaction()                                                          
@login_required                                                                
def account():                                                                 
    return render_template('account.html')                                           
3 Likes

This example was mentioned on #tryton IRC channel by @pokoli.

A post was split to a new topic: How to create a Flask entrypoint to show party

Hi. Thank you for this good example.
I am new at flask, so there are somethings I am still learning.
I try to use this example on my own project, but there is a dictionary call ‘session’, but it isn’t defined anywhere. I could be possible to be this code somehow incomplete.

Thanks

I think you may need to do:

from flask import session
2 Likes

This is a good example to start with. I already implement using part of this code on a simple app.
Is there any other complex example?
I am trying to use a flask dashboard template with flask_tryton, but I have issues to understood how to persist the connection to the tryton database.

You can not. The connection is started with the decorator @tryton.transaction and it is automatically closed on return.

1 Like

Yes! I understood that part.
Maybe is something I still can get it.
I have on my app folder the next
init.py

app = Flask(__name__, static_folder='base/static')

DEBUG = config('DEBUG', default=True, cast=bool)
get_config_mode = 'Debug' if DEBUG else 'Production'
app_config = config_dict[get_config_mode.capitalize()]
app.config.from_object(app_config)

SECRET_KEY = os.urandom(32)
app.config['SECRET_KEY'] = SECRET_KEY
app.config['TRYTON_DATABASE'] = os.environ.get('trytond','Atlas1.2')
app.config['TRYTON_CONFIG'] = 'trytond.conf'
app.config['TRYTON_USER'] = 1
tryton = Tryton(app, configure_jinja=True)
register_blueprints(app)

Party = tryton.pool.get('party.party')
party = Party.search([('id','>',0)])

And it gives me this error:

  File "run.py", line 10, in <module>
    from app import app
  File "/home/fran/my_flask_apps/salita_dashboard/my_app/app/__init__.py", line 41, in <module>
    party = Party.search([('id','>',0)])
  File "/home/fran/.virtualenvs/flask-tryton/lib/python3.6/site-packages/trytond/model/modelsql.py", line 1167, in search
    pool = Pool()
  File "/home/fran/.virtualenvs/flask-tryton/lib/python3.6/site-packages/trytond/pool.py", line 58, in __new__
    database_name = Transaction().database.name
AttributeError: 'NoneType' object has no attribute 'name'

I use some similar code with the example above with no problems, but now I don’t have a clue on why is giving me this error.
Any help would be really appreciated. Regards

Try using decorator @tryton.transaction():

@tryton.transaction()
def get_party():
    Party = tryton.pool.get('party.party')
    party = Party.search([('id','>',0)])
...
1 Like

Now I get it. Thanks

1 Like