예제 #1
0
파일: profile.py 프로젝트: giovamo/Sar
    def import_google_events(self):

        if not self.request.get('selected_calendars'):
            self.response.status = 501
            return

        selected_calendars = json.loads(self.request.get('selected_calendars'))
        credentials = self.user.google_credentials

        if not credentials:
            self.response.status = 501
            return

        http = httplib2.Http()
        http = credentials.authorize(http)
        service = build('calendar', 'v3', http=http)

        page_token = None
        num_imported = 0
        for calendarId in selected_calendars:
            events = service.events().list(calendarId=calendarId, pageToken=page_token).execute()
            if len(events) > 0:
                # creating project
                new_proj = Project(parent=self.user.key)
                new_proj.name = events['summary'][0:25]
                new_proj.put()

                self.user.num_projects += 1
                self.user.put()
                while True:
                    for event in events['items']:
                        if 'dateTime' in event['start']:
                            start_time = datetime.strptime((event['start']['dateTime'])[0:16], '%Y-%m-%dT%H:%M')
                        else:
                            start_time = datetime.strptime((event['start']['date'] + 'T00:00'), '%Y-%m-%dT%H:%M')

                        if 'dateTime' in event['end']:
                            end_time = datetime.strptime((event['end']['dateTime'])[0:16], '%Y-%m-%dT%H:%M')
                        else:
                            end_time = datetime.strptime((event['end']['date'] + 'T00:00'), '%Y-%m-%dT%H:%M')

                        event_title = event['summary'][0:25]
                        event_description = (event['summary'])[0:200]
                        event_url = event['htmlLink']
                        if self.request.get('import_as_billed') == 'true':
                            billed = True
                        else:
                            billed = False
                        self.save_imported_event(new_proj.key, start_time, end_time, event_title, event_description,
                                                 billed, event_url)
                        num_imported += 1

                    page_token = events.get('nextPageToken')
                    if not page_token:
                        break
                    events = service.events().list(calendarId=calendarId, pageToken=page_token).execute()
                    if len(events) == 0:
                        break

        self.response.write(num_imported)
예제 #2
0
파일: views.py 프로젝트: joinEF/people
def edit_project(request, project_id=None):
    # http://wiki.ddenis.com/index.php?title=Django,_add_and_edit_object_together_in_the_same_form

    if project_id:
        print "exists"
        project = get_object_or_404(Project, pk=project_id)
        if request.user not in project.users.all():
            return HttpResponseForbidden()
    else:
        print "doesn't exist"
        project = Project()

    if request.method == "POST":

        form = ProjectForm(request.POST, instance=project)

        if form.is_valid():

            form.save()

            return HttpResponseRedirect(project.get_absolute_url())

    else:

        form = ProjectForm(instance=project)

    if project_id:
        template_name = "edit_project.html"
    else:
        template_name = "new_project.html"

    return render(request, template_name, {"form": form, "project": project})
예제 #3
0
def upload_file(project_id):
    '''Upload .trk/.npz data file to AWS S3 bucket.'''
    start = timeit.default_timer()
    # Use id to grab appropriate TrackEdit/ZStackEdit object from database
    project = Project.get_project_by_id(project_id)

    if not project:
        return jsonify({'error': 'project_id not found'}), 404

    state = load_project_state(project)
    filename = state.file.filename

    # Call function in caliban.py to save data file and send to S3 bucket
    if is_trk_file(filename):
        state.action_save_track()
    elif is_npz_file(filename):
        state.action_save_zstack()

    # add "finished" timestamp and null out state longblob
    Project.finish_project(project)

    current_app.logger.debug('Uploaded file "%s" for project "%s" in %s s.',
                             filename, project_id,
                             timeit.default_timer() - start)

    return redirect('/')
예제 #4
0
def promoteTask(request):
    # Deletes this task, and instead makes it into a project with the same deadline
    U = request.user
    if request.user.is_authenticated() and request.POST:
        # Get task, turn into projects
        taskID = request.POST.get('taskid','')
        taskID = int(taskID)
        Ts = Task.objects.filter(user = U, id = taskID)
        if len(Ts) <= 0:
            # TODO Should bring up a warning box, will be fixed
            # in new layout
            return HttpResponseRedirect('/todolist/invalid_task_access/')
        T = Ts[0]
        # Get name
        tName = T.name
        # Get deadline
        tDeadline = T.deadline
        # Get started, finished
        tStart = T.date_started
        tFinish = T.date_finished
        # Get parentID
        parentID = T.parent_project.id
        T.delete()
        projectColor = genRandomColor();
        P = Project(user = U, name = tName, deadline = tDeadline, date_started = tStart, date_finished = tFinish, parentid = parentID, color = projectColor)
        P.save()
        # TODO Should include new project stuff as well, at least ID
        if request.is_ajax():
            return HttpResponse('Success')
        else :
            return HttpResponseRedirect('/todolist/projects'+str(U.id))
    else :
        return HttpResponseRedirect('todolist/invalid_task_access/')
예제 #5
0
파일: handlers.py 프로젝트: geary/claslite
	def project_new( self, name, settings ):
		owner = current_handler.auth.user.auth_id
		project = Project( name=name, owner=owner, settings=settings )
		project.put()
		return {
			'key': str( project.key() )
		}
예제 #6
0
def create_project():
    config.reload()
    form = ProjectForm()
    ds_forms = dict([
        (cls.populates, cls()) for cls in DataSourceForm.__subclasses__()])

    form.datasource_type.choices = [
        (cls.populates, cls.name) for cls in DataSourceForm.__subclasses__()]
    form.datasource_type.choices.insert(0, (None, "-- Select Data Source --"))
    new_project = Project()

    if form.validate_on_submit():
        form.populate_obj(new_project)
        ds_form = ds_forms[form.datasource_type.data]

        if ds_form.validate():
            new_project.datasource = \
                getattr(models, form.datasource_type.data)()
            ds_form.populate_obj(new_project.datasource)

            db.session.add(new_project)
            db.session.commit()
            flash("New project successfully created.")
            return redirect(url_for('view_project', id=new_project.id))

    return render_template("project/create.html",
                           form=form, ds_forms=ds_forms, project=new_project)
예제 #7
0
def populate():
    p1 = Person('Alice')
    p2 = Person('Anamika')
    p3 = Person('Annie')
    p4 = Person('Anson')
    p5 = Person('Bob')
    p6 = Person('Carol')
    p7 = Person('Don')
    p8 = Person('Evi')

    session.add_all([p1, p2, p3, p4, p5, p6, p7, p8])

    orders = [(p1, 'veggies', 120), (p2, 'veggies', 20), (p3, 'veggies', 120),
              (p4, 'veggies', 10), (p5, 'veggies', 280), (p1, 'ketchup', 80),
              (p1, 'spices', 220), (p1, 'tissues', 50), (p1, 'notebooks', 90),
              (p5, 'ketchup', 80)]
    for person, name, price in orders:
        order = Order(person, name, price)
        session.add(order)

    p1 = Project('BSNL billing', 'alice')
    p2 = Project('BSNL payroll', 'bob')
    p3 = Project('ABC Institute', 'bob')

    pu1 = ProjectUser(p1, 'alice')
    pu2 = ProjectUser(p1, 'carol')
    pu3 = ProjectUser(p1, 'don')
    pu4 = ProjectUser(p2, 'alice')
    pu5 = ProjectUser(p2, 'carol')
    pu6 = ProjectUser(p3, 'don')
    pu7 = ProjectUser(p3, 'carol')

    session.add_all([p1, p2, p3, pu1, pu2, pu3, pu4, pu5, pu6, pu7])

    session.commit()
예제 #8
0
def project_delete(project_id):
    try:
        pass
        # project = Project.get(id=project_id, user=current_user.id)
    except Project.DoesNotExist:
        return jsonify({
            "message":
            "Can't find project with id - `{id}`".format(id=project_id),
            "status":
            "error"
        }), 404

    task_relation_count = Task.select().join(Project).where(
        Project.id == project_id).count()

    if task_relation_count > 0:
        return jsonify({
            "message":
            "Deletion is not possible. The project is connected with tasks",
            "status": "error"
        }), 403

    Project.delete().where(Project.id == project_id).execute()

    # return jsonify({"message": "The project has been successfully deleted", "status": "success"}), 201
    return jsonify({"id": project_id}), 201
예제 #9
0
def projects_form():
    if request.method == "GET":
        project_name = request.args.get("projectName")
        project_types = ProjectType.query.all()

        query = Project.query
        if project_name:
            query = query.filter(
                func.lower(Project.name).startswith(project_name.lower()))
        projects = query.all()
        return render_template("projects.html",
                               project_types=project_types,
                               projects=projects)
    elif request.method == "POST":
        form = request.form
        new_project = Project(
            name=form.get("project_name"),
            description=form.get("project_description"),
            photo_url=form.get("project_photo_url"),
            website_url=form.get("project_website_url"),
            year=form.get("project_year"),
            gge_reduced=form.get("project_gge_reduced"),
            ghg_reduced=form.get("project_ghg_reduced"),
        )
        project_type_name = form.get("project_type_name")
        if project_type_name:
            project_type = ProjectType.query.filter_by(
                type_name=project_type_name).first()
            new_project.type = project_type
        db.session.add(new_project)
        db.session.commit()
        return redirect(url_for("forms.projects_form"), code=303)
    else:
        # raise method not found error
        pass
예제 #10
0
def import_projects(projects=projects):
    from models import Project, ProjectPhoto, ProjectFloorPlan
    for p in projects:
        project = Project(title=p['title'],
            subtitle=p['subtitle'],
            slogan=p['slogan'],
            location=p['location'],
            cover_picture_url=p['cover_picture_url'],
            cover_thumb_url=p['cover_thumb_url'],
            development_status=p['development_status'],
            description=p['description'])
        project.put()
        fps = []
        for fp in p['floor_plans']:
            floor_plan = ProjectFloorPlan(caption=fp['caption'],
                thumb_url=fp['thumb_url'],
                picture_url=fp['picture_url'],
                project=project)
            fps.append(floor_plan)
        db.put(fps)
        photos = []
        for fp in p['photos']:
            photo = ProjectPhoto(caption=fp['caption'],
                thumb_url=fp['thumb_url'],
                picture_url=fp['picture_url'],
                project=project)
            photos.append(photo)
        db.put(photos)
예제 #11
0
def create_project():
    config.reload()
    form = ProjectForm()
    ds_forms = dict([(cls.populates, cls())
                     for cls in DataSourceForm.__subclasses__()])

    form.datasource_type.choices = [(cls.populates, cls.name)
                                    for cls in DataSourceForm.__subclasses__()]
    form.datasource_type.choices.insert(0, (None, "-- Select Data Source --"))
    new_project = Project()

    if form.validate_on_submit():
        form.populate_obj(new_project)
        ds_form = ds_forms[form.datasource_type.data]

        if ds_form.validate():
            new_project.datasource = \
                getattr(models, form.datasource_type.data)()
            ds_form.populate_obj(new_project.datasource)

            db.session.add(new_project)
            db.session.commit()
            flash("New project successfully created.")
            return redirect(url_for('view_project', id=new_project.id))

    return render_template("project/create.html",
                           form=form,
                           ds_forms=ds_forms,
                           project=new_project)
예제 #12
0
 def post(self):
   title = self.request.POST.get('title')
   code = self.request.POST.get('code')
   admins = [Util.getUsernameFromEmail(users.get_current_user().email())]
   project = Project(title=title, code=code, admins=admins)
   project.put()
   self.redirect('/' + project.code + '/organize')
예제 #13
0
def remove_old_projects():
    p = Project.all()
    old_project = p.order('-saved').get()
    if old_project:
        old_date = old_project.saved
        p = Project.all().filter('saved = ', old_date)
        db.delete(p)
예제 #14
0
파일: initdb.py 프로젝트: tobifue/Donatela
def init_db():
    '''
    project1 = Project(location=1, number_participants=2)
    project1.save()
    project2 = Project(location=1, number_participants=1, part_of=project1)
    project2.save()

    user = UserAccount(username="******", email="*****@*****.**", firstname="hans", lastname="mueller", preference="none")
    user = UserAccount(username="******", email="*****@*****.**", firstname="carlo", lastname="arndt", preference="none")
    user.save()
    '''

    business = BusinessAccount(email='*****@*****.**',
                               company_name='business1',
                               fee=10.10,
                               bank_account='AT123456789123')
    business.save()

    organization = Organization(focus='sth',
                                name='brot fuer die Welt',
                                employees=1200,
                                business=business)
    organization.save()

    project = Project(location=2,
                      number_participants=12,
                      organization=organization)
    project.save()
예제 #15
0
파일: views.py 프로젝트: sujithqb/exegesis
def share_project(request):
    try:
        email = request.POST.get('email')
        if not request.POST.get('project-name'):
            project = request.session['project']
            redirection = '/exegesis/artboards?project=' + project
        else:
            project = request.POST.get('project-name')
            redirection = '/exegesis/projects'
        if not Project.objects.filter(project=project, email=email):
            p = Project.objects.filter(project=project)[0]
            description = p.description
            thumbnail = p.thumbnail
            owner = p.owner
            created = p.created
            last_updated = p.last_updated
            screen = p.screen
            density = p.density
            uuid_name = p.uuid
            new_user = Project(email=email, project=project, description=description, share=True, thumbnail=thumbnail,
                               owner=owner, created=created, last_updated=last_updated, density=density, screen=screen,
                               uuid=uuid_name)
            new_user.save()
        return redirect(redirection)
    except:
        print sys.exc_info()
        return render(request, 'wrong.html')
	def	post(self):
		action = self.request.get('action', 'add')
		if action == 'add':
			if len(self.request.get('name'))<2:
				raise Exception("project name must be at least 2 characters long")
			if len(self.request.get('currency'))<1:
				raise Exception("project currency must be at least one character long")
			# create the project and return the new location to go to
			project = Project(name=self.request.get('name'), currency=self.request.get('currency'))
			project.put()
			# add access rights for this user to the new project
			rights = ProjectRights(project=project, user=users.GetCurrentUser(), right=Security.Right_Owner)
			rights.put()
			# redirect to summary
			self.response.out.write("/summary?project=%(key)s" % {'key':project.key()})
		elif action == 'delete':
			# remove me from the projects right list
			project = Project.get(self.request.get('project', ''))
			if (not project):
				raise Exception("Unknown project!")
			# check rights of current user for this project, and deny access if not permitable
			rights = ProjectRights.gql("WHERE user=:user and project=:project", user=users.get_current_user(), project=project).get()
			if rights:
				rights.delete()
			# redirect to my page
			self.response.out.write("/")
		else:
			raise Exception("Unknown action '%(action)s'!" % {'action':action})
예제 #17
0
def submit(request):
    p = Project(project_name=request.POST['project_name'],
                short_desc=request.POST['project_short_desc'],
                project_url=request.POST['project_url'])
    p.save()
    return HttpResponseRedirect(reverse('projects:add'))
    return render(request, 'projects/add.html')
예제 #18
0
    def new_project(payload):
        body = request.get_json()

        # Get information from submitted
        project_name = body.get('project_name', None)
        description = body.get('description', None)
        project_manager = body.get('project_manager', None)

        try:
            # Create new project object
            new_project = Project(project_name=project_name,
                                  description=description,
                                  project_manager=project_manager)
            new_project.insert()

            # Format project object and returnt to client
            formatted_project = {
                "project_name": new_project.project_name,
                "description": new_project.description,
                "project_manager": new_project.project_manager
            }

            return jsonify({
                'success': True,
                'new_project': formatted_project,
            })

        except BaseException:
            print(sys.exc_info())
            abort(400)
예제 #19
0
    def create_project(jwt):
        body = request.get_json()

        try:
            name = body.get('name', None)
            category = body.get('category', None)

            reviewers = Project.query.filter(Project.name.like(name)).count()
            print("current", reviewers)
            if reviewers > 0:
                raise AuthError({
                    'code': 'Bad request',
                    'description': "This project is already existent"
                }, 400)
            reviewer = Project(
                name=name, category=category)
            reviewer.insert()
            return jsonify({
                'success': True,
                'projects': [reviewer.format()]
            })
        except Exception as e:
            print("exception error post reviewer", e)
            print(e)
            if isinstance(e, AuthError):
                raise e
            abort(406)
예제 #20
0
def parse_project(filepath, uploaddate, Document, p_uuid):
    f = csv.DictReader(Document, delimiter=',')
    Document.close()
    for row in f:
        row_dict = row
        m = Project(projectid=p_uuid, path=filepath, upload_date=uploaddate, **row_dict)
        m.save()
예제 #21
0
 def get(self):
     from models import Project
     completed_projects = Project.get_all_complete()
     ongoing_projects = Project.get_all_ongoing()
     self.render('projects.html', 
         completed_projects=completed_projects,
         ongoing_projects=ongoing_projects)
예제 #22
0
def api_create_project(request, *, project_id,project_name,project_level):
    # 只有管理员可以写博客
    #check_admin(request)
    #不能为空
    if not project_id or not project_id.strip():
        raise APIValueError('name', 'name cannot be empty')
    if not project_name or not project_name.strip():
        raise APIValueError('summary', 'summary cannot be empty')
    # 根据传入的信息,构建一条项目数据
    project = Project(
        project_id=project_id,
        project_name=project_name,
        #project_status=project_status,
        #project_stage=project_stage,
        #project_docFlag=project_docFlag,
        project_level=project_level,
        project_manager=request.__user__.user_name
        # project_department=project_department,
        # project_resource=project_resource,
        # project_environment=project_environment
    )
    p_r = yield from Project.findAll(where='project_id=?', args=[project_id])  # 查询id是否已注册,查看ORM框架源码
    if len(p_r) > 0:
        raise APIError('新建项目失败', 'project_id', 'project_id is already in use.')
    # 保存
    yield from project.save()
    return project
예제 #23
0
파일: app.py 프로젝트: prof2k/udacious
def add_project(payload):
    data = request.get_json()
    student = get_or_add_student(payload['sub'])

    # Checks if the request body contains something
    if data: 
        try:    
            new_project = Project(
                name = data['name'],
                description = data['description'],
                project_duration_in_days = data['project_duration'],
                notes = data['notes'],
                image_url = data['image_url'],
                student_id = student.id
            )
            new_project.insert()
        except:
            print(sys.exc_info())
            abort(422)
    else:
        abort(400)
    return jsonify({
        'success': True,
        'project_id': new_project.id
    }), 200
예제 #24
0
파일: views.py 프로젝트: tovmeod/anaf
def project_add_typed(request, project_id, response_format='html'):
    """Project add to preselected parent project"""

    parent_project = None
    if project_id:
        parent_project = get_object_or_404(Project, pk=project_id)
        if not request.user.profile.has_permission(parent_project, mode='x'):
            parent_project = None

    if request.POST:
        if 'cancel' not in request.POST:
            project = Project()
            form = ProjectForm(
                request.user.profile, project_id, request.POST, instance=project)
            if form.is_valid():
                project = form.save()
                project.set_user_from_request(request)
                return HttpResponseRedirect(reverse('projects_project_view', args=[project.id]))
        else:
            return HttpResponseRedirect(reverse('projects'))
    else:
        form = ProjectForm(request.user.profile, project_id)

    context = _get_default_context(request)
    context.update({'form': form, 'project': parent_project})

    return render_to_response('projects/project_add_typed', context,
                              context_instance=RequestContext(request), response_format=response_format)
예제 #25
0
파일: views.py 프로젝트: bmander/proje
def add_project(request, user):
    
    if request.method=="POST":
        # process form
        
        # fail if the name is blank
        name = request.POST['name'].strip()
        if name == "":
            return HttpResponseRedirect( "?error=the+name+needs+to+contain+letters" )
            
        # make and put project
        project = Project(user=user,name=name,updated=datetime.datetime.now())
        project.put()
        
        # increment project_count
        nickname = Nickname.all().filter("user ="******"includes/project_div.html", {'project':{'name':project.name,'id':project.key().id()}} )
    
    return render_to_response( "add_project.html", {'error':request.GET.get('error',None)} )
예제 #26
0
    def post(self, key):
        project = self.getProject(key)
        if project is None:
            project = Project()

        project.name = self.request.get('project[name]')
        project.description = self.request.get('project[description]')
        project.location = self.request.get('project[location]')
        project.type_of_work = self.request.get('project[type_of_work]')
        try:
            spots = int(self.request.get('project[max_volunteers]'))
            if spots <= 0:
                raise ValueError('Below zero')
            project.max_volunteers = spots
        except ValueError as e:
            raise ValidationError(errors={
                'project[max_volunteers]':
                'Must be an integer number above zero'
            })

        project.put()

        error_code = 1 if key == 'new' else 2
        self.redirect('/admin/projects/{}'.format(project.key()),
                      {'error': error_code})
예제 #27
0
    def create_new_project(payload):
        projects = []
        result = {
            "success": True,
        }

        try:
            body = json.loads(request.data)

            title = body['title']
            instructions = body['instructions']
            course_id = body['course_id']

            new_project = Project(title=title,
                                  instructions=instructions,
                                  course_id=course_id)
            new_project.insert()

            projects.append(new_project.format())

        except Exception as e:
            print(e)
            abort(500)

        result['projects'] = projects

        return jsonify(result)
예제 #28
0
def addProject(request):
    if request.session.has_key('logged_in'):
        if request.method == 'POST':
            form = ProjectForm(request.POST, request.FILES)
            if form.is_valid():
                cd = form.cleaned_data
                p = Project(name=cd['name'],
                            url=cd["url"],
                            brief=cd['brief'],
                            cleverbits=cd['cleverbits'],
                            desktop_screenshot=cd['desktop_screenshot'],
                            mobile_screenshot=cd['mobile_screenshot'],
                            description=cd['description'])
                p.save()
                success = True
                return render(request, 'new_project.html',
                              {'success': success})
        else:
            form = ProjectForm()
            return render(request, 'new_project.html', {'form': form})
    else:
        return render(request, 'login.html', {
            'user_login': '******',
            'destination': 'addProject'
        })
예제 #29
0
파일: views.py 프로젝트: sparkmorry/zaec
def register():
	
	if request.method=='POST' and request.form['company']:

		#deal with uploaded files
		full_path = ''
		if request.files['file_path']:
			file_obj = request.files['file_path']
			file_name = file_obj.filename
			full_path = os.path.join(app.config['PROJECT_FOLDER'], file_name)
			file_obj.save(full_path)

		#insert a new project
		project = Project(company = request.form['company'],
			address = request.form['address'],
			invest = request.form['invest'],
			time = request.form['time'],
			name = request.form['name'],
			major = request.form['major'],
			phone = request.form['phone'],
			email = request.form['email'],
			position = request.form['position'],
			holds = request.form['holds'],
			introduction = request.form['introduction'],
			team = request.form['team'],
			business = request.form['business'],
			file_path = full_path
		)
		project.save()
		msg = 'success'

		return render_template('register.html', msg = msg)
	print 'not'
	return render_template('register.html')
예제 #30
0
def remove_project(current_user, id):
    """Deletes project from the db"""
    Project.delete_project(id)
    response = Response("Project deleted",
                        status=200,
                        mimetype="application/json")
    return response
예제 #31
0
 def createProjectNode(self, pType, pId, year, subject, description):
     newProjectNode = Project(pType=pType,
                              pId=pId,
                              year=year,
                              subject=subject,
                              description=description)
     self.graph.cypher.execute(newProjectNode.toCypher())
예제 #32
0
def addproject(request):
    # If a user is authenticated and this is a post request, then
    # we proceed. Otherwise return an invalid page
    U = request.user
    if request.user.is_authenticated() and request.POST:
        deadline = request.POST.get('deadline')
        pid = int(request.POST.get('parentid'))
        projectname = request.POST.get('projectname')
        projectColor = taskViews.genRandomColor();


        P = Project(user=U,name=projectname,date_started=timezone.now(),deadline=deadline,date_finished=timezone.now(),parentid=pid,color=projectColor)
        P.save()

        # Loop through all the tasks posted with this project and create them as
        # unassigned tasks if they don't have deadlines

        index = 1;
        while not (request.POST.get(str(index)) is None):
            newTaskName = request.POST.get(str(index))
            taskDeadline = request.POST.get("time"+str(index))
            timeRequired = request.POST.get("timeReq"+str(index))
            index = index + 1
            if newTaskName == "":
                continue
            else:
                taskViews.createTaskForUserFromList(newTaskName,U,P,taskDeadline,timeRequired)

            
            

        return HttpResponseRedirect('/todolist/projects'+str(U.id))
    else :
        return HttpResponseRedirect('/todolist/invalid_project_add')
예제 #33
0
def add_project(request):

    if request.user.groups.all()[0].name not in ["admin", "qa_lead"]:
        raise PermissionDenied
    else:

        args = {}
        args.update(csrf(request))
        args['active'] = 'active'

        if request.POST:
            proj_name = request.POST['proj_name']
            proj_desc = request.POST['proj_desc']

            if Project.objects.filter(name=proj_name):
                args['message'] = 'Same project already exists.'
                return render_to_response('add_project.html', args)
            else:
                project = Project(name=proj_name, description=proj_desc)
                project.save()
                print project.id
                return HttpResponseRedirect('/project/get/' + str(project.id) +
                                            '/')

        else:

            return render_to_response('add_project.html', args)
예제 #34
0
def create_project(project_id, project_description):
    """Takes arguments and create a new project."""
    db.connect()

    Project.create(project_id=project_id, project_description=project_description)

    db.close()
예제 #35
0
def create_project():
    # with lock:
    # form = CreateProjectForm(request.form)
    # if request.method == 'POST' and form.validate_on_submit():
    debug_set = current_app.config["DEBUG"]
    if debug_set == True:
        print "\n\n\n==========> account->views.py -> create_project() "
        # print "=====> is_private() :", form.is_private.data

    form = CreateProjectForm()
    if form.validate_on_submit():
        new_proj = Project(
            prj_name=form.name.data,
            prj_desc=form.desc.data,
            is_private=form.is_private.data,
            owner=current_user.get_id(),
        )
        prj_id = new_proj.save()
        # Add a user as an owner of a project
        proj = Project.get_project_for_projectid(prj_id)
        print "project.is_private 2:", proj.is_private
        owner_name = current_user.firstname + " " + current_user.lastname
        proj.add_member(name=owner_name, email=current_user.get_id(), role=Project.ROLE_OWNER)
        flash("New project has been created.", category="index_page")
        # Generate a project owner's appkey & save it to ProjectMemberKey coll.
        # keygen = KeyGenerator()
        # key = keygen.getkey(settings.APPKEY_LENGTH)
        key = utils.generate_key()
        prjmemkey = ProjectMemberKey(prj_id=proj.prj_id, appkey=key, member_email=proj.owner)
        prjmemkey.save()
        return redirect(url_for(".list_projects"))

    return render_template("create_project.html", form=form)
예제 #36
0
def create_project():
    #with lock:
    form = CreateProjectForm(request.form)
    if request.method == 'POST' and form.validate():
        new_proj = Project(prj_name=form.name.data, prj_desc=form.desc.data,
            is_private=form.is_private.data, owner=current_user.get_id())
        print 'project.is_private:', new_proj.is_private
        prj_id = new_proj.save()
        # Add a user as an owner of a project
        proj = Project.get_project_for_projectid(prj_id)
        print 'project.is_private 2:', proj.is_private
        owner_name = current_user.firstname + ' ' + current_user.lastname
        proj.add_member(name=owner_name, email=current_user.get_id(), 
            role=Project.ROLE_OWNER)
        flash("New project has been created.", category='index_page')
        # Generate a project owner's appkey & save it to ProjectMemberKey coll.
        #keygen = KeyGenerator()
        #key = keygen.getkey(APPKEY_LENGTH)
        key = utils.generate_key()
        prjmemkey = ProjectMemberKey(prj_id=proj.prj_id, appkey=key, 
            member_email=proj.owner)
        prjmemkey.save()
        return redirect(url_for('.list_projects'))

    return render_template('create_project.html', form=form)
예제 #37
0
 def delete(self, key):
     if auth.user_is_admin():
         Project.get(key).delete()
     else:
         Messages.add('Only and administrator may delete projects. This ' +
                      'incident has been logged.')
     return self.redirect('/projects')
예제 #38
0
def api_projects(*, page='1'):
    page_index = get_page_index(page)
    num = yield from Project.findNumber('count(id)')
    p = Page(num, page_index)
    if num == 0:
        return dict(page=p, projects=())
    projects = yield from Project.findAll(orderBy='created_at desc', limit=(p.offset, p.limit))
    return dict(page=p, projects=projects)
예제 #39
0
 def delete(self, key):
     """Deletes a project."""
     if auth.user_is_admin():
         Project.get(key).delete()
     else:
         Messages.add('Only and administrator may delete projects. This ' +
                      'incident has been logged.')
     return self.redirect('/projects')
예제 #40
0
def create_project(request):
    project = Project(user_id=request.__user__.id, user_name=request.__user__.name, user_image=request.__user__.image, title='', summary='', status=False)
    yield from project.save()
    return {
        '__template__': 'project_edit.html',
        'id': project.id,
        'action': '/api/project/save/'
    }
예제 #41
0
def api_show_projects(*,request, page='1'):
    # 获取项目信息
    page_index = get_page_index(page)
    num = yield from Project.findNumber('count(project_id)')
    p = Page(num, page_index, 5)
    if num == 0:
        return dict(page=p, projects=())
    projects = yield from Project.findAll('project_manager= ?',[request.__user__.user_name],orderBy='created_at asc', limit=(p.offset, p.limit))
    return dict(page=p, projects=projects)
예제 #42
0
    def setUp(self):
        self.project = Project(name='test')
        self.project.save()

        self.taskstatus = TaskStatus(name='test')
        self.taskstatus.save()

        self.task = Task(name='test', project=self.project, status=self.taskstatus)
        self.task.save()
예제 #43
0
def update_project(project_id):
    """Updates the project matching the id project_id.
    Only the parameters to update or to add should be passed in the request body.
    """
    project = Project.objects(id=project_id).get()
    patched = Project(**dict(chain(project.to_dict().items(), request.get_json().items())))
    patched.save()

    return jsonify(patched.to_dict())
예제 #44
0
    def get(self):
        #Wipe datastore of all projects
        projs = Project.all().fetch(1000)
        for proj in projs:
            proj.delete()

        Project(name="Sendery", graph_json = "asdf", mvp_effect = "lasers").put()

        self.response.out.write("done")
예제 #45
0
def create_project():
    user = json.loads(request.data)
    user = Project(user["name"], user["description"], user["address"],
                   int(user["num_people"]), user.get("image", None),
                   user["date"])
    db.session.add(user)
    db.session.commit()

    return json.dumps({"result": True})
예제 #46
0
def api_projects(*, page='1'):
    page_index = get_page_index(page)
    num = yield from Project.findNumber('count(id)')
    p = Page(num, page_index)
    if num == 0:
        return dict(page=p, projects=())
    projects = yield from Project.findAll(orderBy='created_at desc',
                                          limit=(p.offset, p.limit))
    return dict(page=p, projects=projects)
예제 #47
0
    def setUp(self):
        self.group, created = Group.objects.get_or_create(name='test')
        self.user, created = DjangoUser.objects.get_or_create(username=self.username)
        self.user.set_password(self.password)
        self.user.save()
        perspective, created = Perspective.objects.get_or_create(name='default')
        perspective.set_default_user()
        perspective.save()

        ModuleSetting.set('default_perspective', perspective.id)

        self.contact_type = ContactType(name='test')
        self.contact_type.set_default_user()
        self.contact_type.save()

        self.contact = Contact(name='test', contact_type=self.contact_type)
        self.contact.related_user = self.user.profile
        self.contact.set_default_user()
        self.contact.save()

        self.project = Project(name='test', manager=self.contact, client=self.contact)
        self.project.set_default_user()
        self.project.save()

        self.status = TaskStatus(name='test')
        self.status.set_default_user()
        self.status.save()

        self.milestone = Milestone(name='test', project=self.project, status=self.status)
        self.milestone.set_default_user()
        self.milestone.save()

        self.task = Task(name='test', project=self.project, status=self.status, caller=self.contact)
        self.task.set_default_user()
        self.task.save()

        self.task_assigned = Task(name='test', project=self.project, status=self.status)
        self.task_assigned.save()
        self.task_assigned.assigned.add(self.user.profile)

        self.time_slot = TaskTimeSlot(task=self.task, details='test', time_from=datetime.now(), user=self.user.profile)
        self.time_slot.set_default_user()
        self.time_slot.save()

        self.parent = Project(name='test')
        self.parent.set_default_user()
        self.parent.save()

        self.parent_task = Task(
            name='test', project=self.project, status=self.status, priority=3)
        self.parent_task.set_default_user()
        self.parent_task.save()

        self.client = Client()

        self.client.login(username=self.username, password=self.password)
예제 #48
0
def parse_project(filepath, uploaddate, Document, p_uuid):
    f = csv.DictReader(Document, delimiter=',')
    Document.close()
    for row in f:
        row_dict = row
        m = Project(projectid=p_uuid,
                    path=filepath,
                    upload_date=uploaddate,
                    **row_dict)
        m.save()
예제 #49
0
def project():
    if request.method == 'GET':
        return render_template('project.html')
    else:
        project_name = request.form.get('project_name')
        project = Project(name=project_name)
        project.author = g.user
        db.session.add(project)
        db.session.commit()
        return redirect(url_for('index'))
예제 #50
0
 def test_create_project(self):
     """Make sure it creates a project."""
     create_project(project_id='001', project_description='This could be the same.')
     p = Project.select().where(Project.project_id == '001')
     q = Project.delete().where(Project.project_id == '001')
     q.execute()
     self.assertEqual(str(p), ("<class 'models.Project'> SELECT `t1`.`id`,"
                               " `t1`.`project_id`, `t1`.`project_description` "
                               "FROM `project` AS t1 WHERE (`t1`.`project_id` = %s) "
                               "['001']"))
예제 #51
0
def action(project_id, action_type, frame):
    ''' Make an edit operation to the data file and update the object
        in the database.
    '''
    start = timeit.default_timer()
    # obtain 'info' parameter data sent by .js script
    info = {k: json.loads(v) for k, v in request.values.to_dict().items()}

    try:
        # Use id to grab appropriate TrackEdit/ZStackEdit object from database
        project = Project.get_project_by_id(project_id)

        if not project:
            return jsonify({'error': 'project_id not found'}), 404

        state = load_project_state(project)
        # Perform edit operation on the data file
        state.action(action_type, info)

        x_changed = state._x_changed
        y_changed = state._y_changed
        info_changed = state.info_changed

        state._x_changed = state._y_changed = state.info_changed = False

        # Update object in local database
        Project.update_project(project, state)

    except Exception as e:  # TODO: more error handling to identify problem
        traceback.print_exc()
        return jsonify({'error': str(e)}), 500

    tracks = state.file.readable_tracks if info_changed else False

    if x_changed or y_changed:
        encode = lambda x: base64.encodebytes(x.read()).decode()
        img_payload = {}

        if x_changed:
            raw = state.get_frame(frame, raw=True)
            img_payload['raw'] = f'data:image/png;base64,{encode(raw)}'
        if y_changed:
            img = state.get_frame(frame, raw=False)
            img_payload['segmented'] = f'data:image/png;base64,{encode(img)}'
            edit_arr = state.get_array(frame)
            img_payload['seg_arr'] = edit_arr.tolist()

    else:
        img_payload = False

    current_app.logger.debug('Action "%s" for project "%s" finished in %s s.',
                             action_type, project_id,
                             timeit.default_timer() - start)

    return jsonify({'tracks': tracks, 'imgs': img_payload})
예제 #52
0
    def test_create_project_no_duplicate(self):
        """Make sure you can't create projects with duplicate IDs."""
        Project.create(project_id='001', project_description='Testing purpose.')

        from peewee import IntegrityError
        with self.assertRaises(IntegrityError):
            Project.create(project_id='001', project_description='This could be the same.')

        # Delete the instance created
        q = Project.delete().where(Project.project_id == '001')
        q.execute()
예제 #53
0
def put_project(current_user, id):
    """Edits project in the db"""
    request_data = request.get_json(force=True)
    Project.update_project(
        id,
        request_data["title"],
    )
    response = Response("Project updated",
                        status=200,
                        mimetype="application/json")
    return response
예제 #54
0
파일: remote.py 프로젝트: waldvogel/taxi
    def get_projects(self):
        projects_url = 'project/all.json'

        self._login()

        response = self._request(projects_url)
        response_body = response.read()

        response_json = json.loads(response_body)
        projects = response_json['command']['projects']['project']
        activities = response_json['command']['activities']['activity']
        activities_dict = {}

        for activity in activities:
            a = Activity(int(activity['id']),
                    activity['name'], activity['rate_eur'])
            activities_dict[a.id] = a

        projects_list = []
        i = 0
        print '%d projects found' % len(projects)

        for project in projects:
            p = Project(int(project['id']), project['name'],\
                    project['status'], project['description'],\
                    project['budget'])
            i += 1

            if p.status == 1:
                activities = project['activities']['activity']

                # Sometimes the activity list just contains an @attribute
                # element, in this case we skip it
                if isinstance(activities, dict):
                    continue

                # If there's only 1 activity, this won't be a list but a simple
                # element
                if not isinstance(activities, list):
                    activities = [activities]

                for activity in activities:
                    try:
                        if int(activity) in activities_dict:
                            p.add_activity(activities_dict[int(activity)])
                    except ValueError:
                        print("Cannot import activity %s for project %s"\
                            " because activity id is not an int" %
                            (activity, p.id))

            projects_list.append(p)

        return projects_list
예제 #55
0
    def construct_Single_Project(self):
        """
        This method constucts a Project with one of each
        of the objects from the hierarchy and returns it.
        """ 
        project = Project("PojectTestName", "ProjectTestDescription")
        groupone = BudgetGroup("BGTestName", "BGTestDescription")
        itemone = BudgetItem("BITestName", "BITestDescription", 2, 5)

        groupone.add(itemone)              
        project.add(groupone)

        return project
예제 #56
0
 def get(self, id_or_slug):
     from models import Project
     completed_projects = Project.get_all_complete()
     ongoing_projects = Project.get_all_ongoing()
     try:
         id = int(id_or_slug, 10)
         project = Project.get_by_id(id)
     except ValueError:
         project = Project.get_by_slug(id_or_slug)
     self.render('project_information.html', 
         project=project,
         completed_projects=completed_projects,
         ongoing_projects=ongoing_projects)
예제 #57
0
def add(request):
	if request.method == 'POST':
		error = False
		p = Project()
		p.date_time_last_updated = datetime.datetime.now()
		p.last_updated_by = request.user
		form = forms.ProjectForm(request.POST, instance=p)
		if form.is_valid():
			form.save()			
		else:
			error = True
	projects = Project.objects.all().order_by('project_code')
	form = forms.ProjectForm()
	return render_to_response('projects/add.html', locals() )