예제 #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
파일: app.py 프로젝트: ofirpe/projSystem
def proj_investments(project_id):
    selected_proj = [
        row for row in Projects.select().where(
            Projects.project_id == project_id).dicts()
    ]

    users_list = [
        row for row in Users.select(
            UserProject.user.first_name,
            UserProject.user.last_name,
            UserProject.role.title,
        ).join(UserProject).join(Roles).switch(UserProject).join(
            Projects).where(Projects.project_id == project_id).dicts()
    ]

    inv_list = [
        row for row in Projects.select(Projects, ProjectInvestment).join(
            ProjectInvestment).order_by(Projects.project_name).where(
                Projects.project_id == project_id).dicts()
    ]

    total = ProjectInvestment.select(
        peewee.fn.sum(ProjectInvestment.investment).alias('sum')).where(
            ProjectInvestment.project_id == project_id).scalar()

    return render_template('proj_investments.j2',
                           inv=inv_list,
                           proj=selected_proj[0],
                           users=users_list,
                           total=str(total))
예제 #3
0
파일: app.py 프로젝트: ofirpe/projSystem
def jsonproj():
    if request.method == 'GET':
        all_proj = [row for row in Projects.select().dicts()]
        selection = request.args.get('selection')
        return_value = Projects.select().where(
            Projects.project_id == selection)

        return render_template('projects.j2',
                               proj=return_value,
                               all_proj=all_proj)
예제 #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 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
예제 #6
0
def before_request():
    g.db = connect_db()
    Slot_Conf.set_db(g.db)
    Job.set_db(g.db)
    TimeInfo.set_db(g.db)
    slotStartEnd.set_db(g.db)
    Projects.set_db(g.db)
    Results.set_db(g.db)
    ProjNames.set_db(g.db)
    SlotTimes.set_db(g.db)
    ProjectTimes.set_db(g.db)
예제 #7
0
def before_request():
	g.db = connect_db()
	Slot_Conf.set_db(g.db)
	Job.set_db(g.db) 
	TimeInfo.set_db(g.db)
	slotStartEnd.set_db(g.db)
	Projects.set_db(g.db)
	Results.set_db(g.db)
	ProjNames.set_db(g.db)
	SlotTimes.set_db(g.db)
	ProjectTimes.set_db(g.db)
예제 #8
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})
예제 #9
0
 def POST():
     '''
     TODO: 全ファイルの情報をとってこようとも思ったけど、プロジェクトがデカくなるとヘヴィな
     '''
     targ = Projects().get(entry_id)[0]
     file_path = request.json['file_path']
     full_path = [_path for _path in targ.full_files_path_as_tree() if _path.endswith(file_path)][0]
     with open(full_path, 'r') as f:
         content = f.read()
     return jsonify({
         'id': targ.id,
         'name': targ.name,
         'file_path': file_path,
         'content': content,
     })
예제 #10
0
    def get(self):
        dataHours = []
        projects = []
        dailyHours = dict()

        for p in Projects.all():
            dailyHours[p.name] = datetime.datetime.min
            projects.append(p.name)

        for j in JobHours.all():
            if j.started:
                j.restart()
            dataHours.append(DataJobHours(j))
            tmp = j.hours - datetime.datetime.min
            dailyHours[j.project.name] += tmp

        hoursArray = []
        for k, v in dailyHours.iteritems():
            v = getHours(v)
            hoursArray.append([k, v])

        template_values = {
            'projects': projects,
            'hours': dataHours,
            'daily': hoursArray,
            'current_user': users.get_current_user(),
            'logout_url': users.create_logout_url('/')
        }
        path = os.path.join(os.path.dirname(os.path.dirname(__file__)),
                            'templates', 'index.html')
        self.response.out.write(template.render(path, template_values))
예제 #11
0
    def get(self):
        dataHours = []
        projects = []
        dailyHours = dict()

        for p in Projects.all():
            dailyHours[p.name] = datetime.datetime.min
            projects.append(p.name)

        for j in JobHours.all():
            if j.started:
                j.restart()
            dataHours.append(DataJobHours(j))
            tmp = j.hours - datetime.datetime.min
            dailyHours[j.project.name] += tmp

        hoursArray = []
        for k,v in dailyHours.iteritems():
            v = getHours(v)
            hoursArray.append([k,v])

        template_values = {
            'projects':projects,
            'hours':dataHours,
            'daily':hoursArray,
            'current_user': users.get_current_user(),
            'logout_url': users.create_logout_url('/')
            }
        path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'templates', 'index.html')
        self.response.out.write(template.render(path, template_values))
예제 #12
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'
예제 #13
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')
예제 #14
0
def dash():
    if request.method == 'POST':
        #take data from form and put into database
        #TODO(rushiagr): do session expire check here
        user_personal_info = UserPersonalInfo(
            email=session.get('userEmail'),
            name=request.form.get('name'),
            title=request.form.get('position'),
            location=request.form.get('location'),
            summary=request.form.get('summary'),
        )
        user_personal_info.put()
        experience = Experience(
            email=session.get('userEmail'),
            position=request.form.get('experience_role'),
            description=request.form.get('experience_description'),
        )
        experience.put()
        projects = Projects(
            email=session.get('userEmail'),
            project_name=request.form.get('project_name'),
            description=request.form.get('project_description'),
        )
        projects.put()
        education = Education(
            email=session.get('userEmail'),
            duration=request.form.get('education_duration'),
            program=request.form.get('education_program'),
            institution=request.form.get('education_institution'),
            score_achieved=request.form.get('education_score'),
            score_out_of='10',
        )
        education.put()
        return render_template('profile.html',
                               session_user=session.get('userEmail'),
                               user_personal_info=user_personal_info,
                               experience=experience,
                               projects=projects,
                               education=education)
        
    elif request.method == 'GET':
        return render_template('edit_profile.html', session_user=session.get('userEmail'))
예제 #15
0
def update_url(request, url_id, *args, **kwargs):
    """update url"""
    body = json.loads(request.body)
    user = request.user
    project_id = body.get("project")
    project = Projects.get_by_id(project_id)
    if not project:
        return dict(error="No such project "+ str(project_id))
    kwds = UrlService._parse_keywords(**body)
    url = UrlService.update_url(user.key, project.key, url_id, **kwds)
    return url.to_dict()
예제 #16
0
파일: app.py 프로젝트: ofirpe/projSystem
def newinv():
    if request.method == 'GET':
        proj = [row for row in Projects.select().dicts()]
        return render_template('newinv.j2', proj=proj)
    new_inv = ProjectInvestment(**request.form)

    try:
        new_inv.save()
    except peewee.IntegrityError as err:
        return str(err)
    return redirect(url_for('investments'))
예제 #17
0
class PositiveTest(TestCase):
    def test_creating_user(self):
        """
        Always create the project with required parameters
        - Project name
        - Project owner
        - Project description
        """
        
        self.Project = Projects(
            project_name = "test message",
            #account_id = 1,
            #language = 'nl',
            #present_languages = 'nl',
            #has_attachment = True

        )
        print self.Project.save()
        
        
        self.assertEqual(1 + 1, 2)
예제 #18
0
def create_url(request, *args, **kwargs):
    """create a new url"""
    body = json.loads(request.body)
    user = request.user
    log.info(user)
    project_id = body.get("project")
    log.info(project_id)
    project = Projects.get_by_id(id=project_id)
    log.info(project)
    if not project:
        return dict(error="No such project "+ str(project_id))
    url = UrlService.create_url(user.key, project.key, **body)
    return url.to_dict()
예제 #19
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")
예제 #20
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()
예제 #21
0
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
예제 #22
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")
예제 #23
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),
            })
예제 #24
0
 def GET():
     projects = Projects()
     return jsonify(
         {'entries': [proj._asdict() for proj in projects.get_all()]}
     )
예제 #25
0
파일: app.py 프로젝트: ofirpe/projSystem
def investments():
    inv_list = [
        row for row in Projects.select(Projects, ProjectInvestment).join(
            ProjectInvestment).order_by(Projects.project_name).dicts()
    ]
    return render_template('investments.j2', inv=inv_list)
예제 #26
0
def get_project(id):
    return jsonify(Projects.get_project_by_id(id).to_dict())
예제 #27
0
def change_html(id):
    project = Projects.get_project_by_id(id)
    project.html_code = request.form.get('html_code')
    db.session.add(project)
    db.session.commit()
    return get_project(id)
예제 #28
0
def deploy(project_id):
    project = Projects.get_project_by_id(project_id)
    return project.html_code
예제 #29
0
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
예제 #30
0
async def get_user_projects(telegram_id: int):
    return await Project_Pydantic.from_queryset(
        Projects.filter(telegram_id=telegram_id).all())