1
\$\begingroup\$

Is it a good practice to separate Logic from Request controller in an Api ?

Without separation:

@app.mod_portal.bp.route('scan', methods=['GET'])
@login_required
def scan_all():
    print(vars(app.mod_portal.bp))

    portals = Portal.get_all(g.user.id)
    for portal in portals:
        scan(portal.id) # check for json error here

    return make_response(jsonify({'status': 'ok'}), 200)


@app.mod_portal.bp.route('<id>/scan', methods=['GET'])
@login_required
def scan(id):
    portal = Portal.get(id)

    datasets = extract_dataset_from_portal(portal.url)
    Dataset.delete_all(portal.id)

    for dataset in datasets:
        Dataset.create(dataset, portal.id)

    return make_response(jsonify({'status': 'ok'}), 200)

With separation

def logic_scan(id):
    portal = Portal.get(id)
    datasets = extract_dataset_from_portal(portal.url)
    Dataset.delete_all(portal.id)

    for dataset in datasets:
        Dataset.create(dataset, portal.id)

@app.mod_portal.bp.route('scan', methods=['GET'])
@login_required
def scan_all():

    portals = Portal.get_all(g.user.id)
    for portal in portals:
        try:
            logic_scan(portal.id)
        except # check error here

    return make_response(jsonify({'status': 'ok'}), 200)


@app.mod_portal.bp.route('<id>/scan', methods=['GET'])
@login_required
def scan(id):
    try:
      logic_scan(id)
    except # check error here
    return make_response(jsonify({'status': 'ok'}), 200)

Maybe the second example is better because I can handle different type of exception and return a different error message. What is the standard for that ? In case of separation, do you create another file for that ? like apiname_controller.py and apiname_logic.py or something like that ?

\$\endgroup\$
  • \$\begingroup\$ I can't say which are best practices in python but I always do it in C#. It also has the nice advantage to make my tests much much easier to write and more focused (not to mention code reuse) \$\endgroup\$ – Adriano Repetti Jul 20 '17 at 16:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.