コード例 #1
0
def register_project():
    print(current_user.id)
    form = RegisterProjectForm()
    if request.method == 'POST' and form.validate_on_submit():
        project = Projects(name=form.name.data,
                           short_description=form.short_description.data,
                           full_description=form.full_description.data,
                           owner_id=current_user.id)
        resp = check_project(form)
        # checking is all data in form is good
        if resp != 'OK':
            err_attr = getattr(form, resp[0])
            err_attr.errors.append(resp[1])
            return render_template('register_project.html',
                                   form=form,
                                   title='Register project')
        sesion = db_session.create_session()
        # getting this project id
        last_id = sesion.query(func.max(Projects.id)).one()

        # saving image for this project
        image = request.files.get('image_field')
        if not last_id[0]:
            last_id = 1
        else:
            last_id = int(last_id[0]) + 1
        if image and image.filename.rsplit('.')[1] in ['png', 'jpg', 'jpeg']:
            filename = f'{current_user.id}_{last_id}.jpg'
            global_file_path = os.path.join(
                app.config['UPLOAD_FOLDER'],
                os.path.join('project_imgs', filename))
            image.save(global_file_path)
            project.image_path = url_for(
                'static', filename=f'imgs/project_imgs/{filename}')
        else:
            project.image_path = url_for(
                'static', filename='imgs/project_imgs/no_project_image.jpg')
        for username in form.collaborators.data.split(', '):
            user = sesion.query(User).filter(
                User.username == username.strip()[1:]).first()
            if user:
                project.collaborators.append(user)
        sesion.add(project)
        sesion.commit()
        sesion.close()
        print('subprocess with last_id:', last_id)

        probable_tags = analyze_description(last_id)
        # subprocess.call(f'python analyze_description.py {last_id}', shell=True)
        if len(probable_tags) > 0:
            response = make_response(
                redirect(
                    url_for('blog.check_tags',
                            id=str(last_id),
                            tags=','.join(probable_tags))))
            return response
        return redirect(url_for('base'))
    return render_template('register_project.html',
                           form=form,
                           title='Register project')
コード例 #2
0
def create_project():
    args = {}
    for k in request.form:
        args[k] = request.form[k]
    args['total_amount'] = int(request.form.get('total_amount', 0))
    args['amount'] = int(request.form.get('amount', 0))
    p = Projects(**args)
    db_session.add(p)
    db_session.commit()
    return json.dumps(p.json()), 200
コード例 #3
0
def lambda_handler(event, context):


    project_ids = gdocs.get_project_ids(FILE_KEY)
    if not project_ids:
        return "No projects found"
    print project_ids
    projects = Projects().get_projects_by_id_list([str(_id) for _id in project_ids])
    priority_list(projects)
    return 'Done'
コード例 #4
0
ファイル: app.py プロジェクト: ofirpe/projSystem
def newp():
    if request.method == 'GET':
        return render_template('newp.j2')
    new_project = Projects(**request.form)

    try:
        new_project.save()
    except peewee.IntegrityError:
        return abort(403, 'Project exists')
    return render_template('newp.j2')
コード例 #5
0
def projectadd(request):
    tips = ''
    if request.method == 'POST':
        name = request.POST.get('projectname', '')
        remark = request.POST.get('remark', '')
        is_exist = Projects.objects.filter(projectname=name)
        if is_exist:
            tips = 'existed'
        else:
            r = Projects(projectname=name, remark=remark)
            r.save()
            tips = 'ok'
    return JsonResponse({'tips': tips})
コード例 #6
0
def generate():
    if request.method == 'POST':
        project_name = request.form.get('project_name')
        style = request.form.get('style')
        # Prep model on basis of which mdoel is requested
        model = prep_model()
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser still
        # submits an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            new_project = Projects(project_name)
            db.session.add(new_project)
            db.session.commit()
            project_id = new_project.id
            file_name = str(project_id) + '.png'
            file_address = os.path.join(os.getcwd(),
                                        app.config['UPLOAD_FOLDER'], file_name)
            file.save(file_address)
            output_folder = os.path.join(os.getcwd(),
                                         app.config['OUTPUT_FOLDER'])
            html = model.convert_single_image(output_folder,
                                              png_path=file_address,
                                              print_generated_output=0,
                                              get_sentence_bleu=0,
                                              original_gui_filepath=None,
                                              style=style)
            project = Projects.get_project_by_id(project_id)
            project.html_code = html
            project.deploy_url = f'http://localhost:5000/deploy/{project_id}'
            db.session.add(project)
            db.session.commit()
            K.clear_session()
            return get_project(project_id)
    else:
        return render_template('generator_page.html')
コード例 #7
0
    def get(self, p='', n=''):
        try:
            p = urllib.unquote(p)
            n = urllib.unquote(n)

            pj = Projects.all().filter('name =', p).get()
            if not pj:
                pj = Projects(name=p)
                pj.put()

            new = False
            jh = pj.jobhours_set.filter('name =', n).get()
            if not jh:
                descr = self.request.get('descr')
                jh = JobHours(name = n,\
                    hours = datetime.datetime.min,\
                    descr = descr, project = pj.key())
                jh.put()
                new = True

            method = self.request.get('method')
            if method == 'delete':
                jh.delete()
                Respond(self, 0, "")
            elif method == 'start':
                jh.start()
                Respond(self, 0, "")
            elif method == 'stop':
                jh.stop()
                Respond(self, 0, jh.getHours())
            elif new:
                Respond(self, 0, jh.getHours())
            else:
                Respond(self, 1, "Task already exists!")
        except:
            Respond(self, 1, "Unexpected error!")
            logging.exception("Error")
コード例 #8
0
def init_db():
    # Create the fixtures
    print("test")
    task1 = Tasks(name="Test1",
                  description="OUia sad asd",
                  priority=1,
                  difficulty=2)
    task2 = Tasks(name="Test2",
                  description="Ceci n'est pas une fixture",
                  priority=3,
                  difficulty=0)

    newSprint = Sprints(name="new sprint",
                        deadline=datetime.now,
                        tasks=[task1, task2])

    newProject = Projects(name="Test", description="Oui", sprints=[newSprint])
    newProject.save()

    User1 = Users(
        name="User1",
        password="******",
        email="*****@*****.**")
    User1.save()
コード例 #9
0
ファイル: main.py プロジェクト: jhcxavier/Back-End-PersPage
def handle_projects():

    if request.method == 'POST':
        body = request.get_json()

        if body is None:
            raise APIException(
                "You need to specify the request body as a json object",
                status_code=400)
        if "name" not in body:
            raise APIException('You need to specify the name', status_code=400)
        if "description" not in body:
            raise APIException('You need to specify the description',
                               status_code=400)
        if "image" not in body:
            raise APIException('You need to specify the images',
                               status_code=400)
        if "github" not in body:
            raise APIException('You need to specify the github address',
                               status_code=400)
        if "demo" not in body:
            raise APIException('You need to specify the demo\'s link')

        project1 = Projects(name=body['name'],
                            description=body["description"],
                            image=body['image'],
                            github=body['github'],
                            demo=body['demo'])
        db.session.add(project1)
        db.session.commit()
        return 'ok', 200

    if request.method == "GET":
        all_projects = Projects.query.all()
        all_projects = list(map(lambda x: x.serialize(), all_projects))
        return jsonify(all_projects), 200
コード例 #10
0
ファイル: helpers.py プロジェクト: Shmiggit/Flask-ReDB
def addNewProject(form):
    # FETCH DATA
    # Get data from form
    code = form.code.data
    name = form.name.data
    plants = form.plants.data
    pm = form.pm.data
    pp = form.pp.data
    site = form.site.data
    role = form.role.data
    dict_services = {
        "fs": form.fs.data,
        "ff": form.ff.data,
        "eya": form.eya.data,
        "dd": form.dd.data,
        "cm": form.cm.data,
        "om": form.om.data,
        "bdd": form.bdd.data,
        "vdd": form.vdd.data,
        "gov": form.gov.data,
        "bs": form.bs.data,
        "oth": form.oth.data
    }

    other = form.other.data
    #description = form.description.data

    # CHECK DATA
    # Perform sanity checks:
    form_errors = False

    # Verify name is not already in use in database:
    db_project = Projects.query.filter_by(name=name).first()
    if db_project != None:
        form_errors = True
        form.name.errors.append(
            'Project already registered under that name. See project code ' +
            str(db_project.code))

    # Verify code is not already in use in database:
    db_project = Projects.query.filter_by(code=code).first()
    if not db_project == None:
        form_errors = True
        form.code.errors.append(
            'Project already registered under that code. See project name ' +
            str(db_project.name))

    # Verify PM and PP are still staffmembers
    db_pm = Users.query.filter_by(staffnum=pm).first()
    db_pp = Users.query.filter_by(staffnum=pp).first()
    if db_pm == None or db_pp == None:
        form_errors = True
        form.pm.errors.append(
            'Project Manager and Project Principal should be current staffmembers'
        )

    # Verify PM and PP are not the same person
    if pm == pp:
        form_errors = True
        form.pm.errors.append(
            'Project Manager and Project Principal should not be the same person.'
        )
        form.pp.errors.append(' ')

    # Verify at least one service has been selected
    if all(boolean == False for key, boolean in dict_services.items()):
        form_errors = True
        for key, boolean in dict_services.items():
            if key == 'eya':
                form.eya.errors.append('Please select at least one service.')
            else:
                form[key].errors.append('')

    elif dict_services['oth'] == True and other == '':
        form_errors = True
        form.other.errors.append(
            'Please specify which other service was provided.')
        form.oth.errors.append('')

    # If errors have been found, return form for completion
    if form_errors == True:
        result = {"errors": form}
        return result

# CREATE NEW PROJECT IN DATABASE
# Fetch role from db
    db_role = Roles.query.filter_by(short=role).first()

    # Create new project
    db_project = Projects(
        code=code,
        name=name,
        role_id=db_role.id,
        services=dict_services,
        #description=description,
        link=site,
        pm_id=db_pm.staffnum,
        pp_id=db_pp.staffnum
        #client_id=db_client.id
    )

    db.session.add(db_project)

    for plant in plants:
        # Find plant in database
        db_plant = Plants.query.filter_by(id=plant).first()
        # Add project - plants relationship
        db_project.plants.append(db_plant)

    # Commit session to database & check for integrity errors
    try:
        # Updating database
        db.session.commit()
        # Redirect user to home page
        return db_project

    # Checks for primary key, null and uniques - returns an integrity error if clash occurs
    except IntegrityError:
        # Rollback changes
        db.session.rollback()
        result = False
        return result
コード例 #11
0
def create_project(request):
    form = CreateProjectForm()
    if request.method == 'POST':
        title = request.POST.get("title")
        owner = request.user.username
        version = request.POST.get("version")
        client = request.POST.get("client")
        description = request.POST.get("description")
        status = "Open"
        payout = request.POST.get("payout")

        projects = Projects(title=title,
                            owner=owner,
                            version=version,
                            client=client,
                            description=description,
                            status=status,
                            payout=payout)

        if is_a_num(request.POST.get("payout")):

            if int(request.POST.get("payout")) <= int(
                    User.objects.get(username=owner).userprofile.balance):
                new_balance = int(
                    User.objects.get(
                        username=owner).userprofile.balance) - int(
                            request.POST.get("payout"))
                user = User.objects.get(username=owner)
                user.userprofile.balance = new_balance
                #update balance
                user.save()

                #add project
                projects.save()

                return HttpResponseRedirect("/projects/")

            else:

                return render(
                    request, 'BuildPythonPleaseGUI/create_project.html', {
                        "form":
                        CreateProjectForm(
                            initial={
                                "title": title,
                                "version": version,
                                "client": client,
                                "description": description,
                            }),
                        "form_error":
                        True,
                    })

        else:

            return render(
                request, 'BuildPythonPleaseGUI/create_project.html', {
                    "form":
                    CreateProjectForm(
                        initial={
                            "title": title,
                            "version": version,
                            "client": client,
                            "description": description,
                            "payout": payout
                        }),
                    "form_error":
                    True,
                })
    else:

        return render(
            request, 'BuildPythonPleaseGUI/create_project.html', {
                "form": form,
                "form_error": False,
                'notifications': notifications(request),
            })