[PATCH 5/5] Update the API code

Pierre-Yves Chibon pingou at pingoured.fr
Sun Jan 27 13:11:29 UTC 2013


Now the API makes use of the form to validate the input when the request uses POST
for GET requests though, we need to check the argument given to the request.
---
 coprs_frontend/coprs/views/api_ns/api_general.py | 127 +++++++++++++++--------
 1 file changed, 84 insertions(+), 43 deletions(-)

diff --git a/coprs_frontend/coprs/views/api_ns/api_general.py b/coprs_frontend/coprs/views/api_ns/api_general.py
index adc851d..e399558 100644
--- a/coprs_frontend/coprs/views/api_ns/api_general.py
+++ b/coprs_frontend/coprs/views/api_ns/api_general.py
@@ -1,9 +1,14 @@
+import datetime
+import random
+import string
 import time
 
 import flask
 
+from coprs import app
 from coprs import db
 from coprs import exceptions
+from coprs import forms
 
 from coprs.views.misc import login_required
 
@@ -13,12 +18,24 @@ from coprs.logic import builds_logic
 from coprs.logic import coprs_logic
 
 
+def generate_api_token(size=30):
+    """ Generate a random string used as token to access the API
+    remotely.
+
+    :kwarg: size, the size of the token to generate, defaults to 30
+        chars.
+    :return: a string, the API token for the user.
+
+    """
+    return ''.join(random.choice(string.ascii_lowercase) for x in range(size))
+
+
 @api_ns.route('/')
 def api_home():
     """ Renders the home page of the api.
     This page provides information on how to call/use the API.
     """
-    return flask.render_template('coprs/api.html')
+    return flask.render_template('api.html')
 
 
 @api_ns.route('/new/', methods = ["GET", "POST"])
@@ -33,16 +50,12 @@ def api_new_token():
     db.session.add(user)
     db.session.commit()
     flask.g.user = user
-    return flask.redirect(flask.url_for('misc.api'))
+    return flask.redirect(flask.url_for('api_ns.api_home'))
 
 
- at api_ns.route('/add/<name>/<chroots>/',
-    defaults={'repos':"", 'initial_pkgs':""})
- at api_ns.route('/add/<name>/<chroots>/<repos>/',
-    defaults={'initial_pkgs':None})
- at api_ns.route('/add/<name>/<chroots>/<repos>/<initial_pkgs>/')
+ at api_ns.route('/copr/new/', methods=['POST'])
 @login_required
-def api_add_copr(name, chroots, repos="", initial_pkgs=""):
+def api_new_copr():
     """ Receive information from the user on how to create its new copr,
     check their validity and create the corresponding copr.
 
@@ -54,43 +67,71 @@ def api_add_copr(name, chroots, repos="", initial_pkgs=""):
         build in this new copr
 
     """
-    infos = []
-    copr = coprs_logic.CoprsLogic.add_coprs(
-        name=name.strip(), 
-        repos=" ".join([repo.strip() for repo in repos.split(',')]),
-        owner=flask.g.user,
-        selected_chroots=[chroot.strip()
-            for chroot in chroots.split(',')]
-        )
-    infos.append('New copr was successfully created.')
-
-    if initial_pkgs:
-        builds_logic.BuildsLogic.add_build(
-            pkgs=" ".join([pkg.strip() for pkg in initial_pkgs.split(',')]),
-            copr=copr,
-            owner=flask.g.user)
-        infos.append('Initial packages were successfully submitted '
-                'for building.')
-    return '{"output" : "%s"}' % ("\n".join(infos))
-
-
- at api_ns.route('/list/<username>/', methods=['GET'])
-def api_list_copr(username):
+    form = forms.CoprFormFactory.create_form_cls()(csrf_enabled=False)
+    if form.validate_on_submit():
+        infos = []
+        try:
+            copr = coprs_logic.CoprsLogic.add(
+                name=form.name.data.strip(),
+                repos=" ".join([repo.strip()
+                    for repo in form.repos.data.split(',')]),
+                user=flask.g.user,
+                selected_chroots=form.selected_chroots,
+                description=form.description.data,
+                instructions=form.instructions.data,
+                check_for_duplicates=True,
+                )
+            infos.append('New copr was successfully created.')
+
+            if form.initial_pkgs.data:
+                builds_logic.BuildsLogic.add_build(
+                    pkgs=" ".join([pkg.strip()
+                        for pkg in form.initial_pkgs.data.split(',')]),
+                    copr=copr,
+                    owner=flask.g.user)
+                infos.append('Initial packages were successfully submitted '
+                        'for building.')
+
+            output = '{"output" : "%s"}' % ("\n".join(infos))
+            db.session.commit()
+        except exceptions.DuplicateCoprNameException, err:
+            output = '{"upload": "notok", "error": "%s"}' % err
+            db.session.rollback()
+
+    else:
+        output = '{"upload": "notok", "error": "Invalid request"}'
+
+    return flask.Response(output, mimetype='application/json')
+
+
+ at api_ns.route('/owned/')
+def api_list_copr():
     """ Return the list of coprs owned by the given user.
 
     :arg username: the username of the person one would like to the
         coprs of.
+
     """
-    query = coprs_logic.CoprsLogic.get_multiple(flask.g.user,
-        user_relation = 'owned', username = username)
-    output = '{"repos":[\n'
-    repos = query.all()
-    cnt = 0
-    for repo in repos:
-        output += '{"name" : "%s", "repos" : "%s"}\n' % (
-            repo.name, repo.repos)
-        cnt = cnt + 1
-        if cnt < len(repos):
-            output += ','
-    output += "]}\n"
-    return output
+    if 'username' in flask.request.args:
+        username = flask.request.args['username']
+        query = coprs_logic.CoprsLogic.get_multiple(flask.g.user,
+            user_relation = 'owned', username = username)
+        repos = query.all()
+        output = '{"repos":[\n'
+        cnt = 0
+        for repo in repos:
+            output += '{'\
+            '"name" : "%s", '\
+            '"repos" : "%s", '\
+            '"description": "%s", '\
+            '"instructions": "%s" '\
+            '}\n' % (repo.name, repo.repos, repo.description,
+                repo.instructions)
+            cnt = cnt + 1
+            if cnt < len(repos):
+                output += ','
+        output += "]}\n"
+    else:
+        output = '{"download": "notok", "error": "Invalid request"}'
+
+    return flask.Response(output, mimetype='application/json')
-- 
1.8.1



More information about the copr-devel mailing list