def project(projectname): project = Project.get_project_by_name(projectname) if project is None: return redirect(url_for('error.not_found_error')) creator = Project.get_creator(projectname) return render_template("project/project.html", project=project, creator=creator)
def upload(): if 'input_file' not in request.files: return badRequest('no input file') file = request.files['input_file'] if Project.allowed_file(file.filename): errors = [] for field in ['project_title', 'authors']: if request.form.get(field) is None: errors.append(f"{field} field missing in request") if errors != []: return badRequest(errors) filename = secure_filename(file.filename) new_project = Project() new_project.owner = current_user.id new_project.authors = request.form.get('authors') new_project.title = request.form.get('project_title') new_project.hashFilename(filename) new_project.file_data = file.read() new_project.pdf_page_count = request.form.get('pdf_page_count') db.session.add(new_project) db.session.commit() return jsonify('upload success'), 201 return errorResponse(415, 'upload a .pdf file!')
def project_users(projectname): project = Project.get_project_by_name(projectname) if project is None: return redirect(url_for('error.not_found_error')) users_and_roles = Project.get_project_users_and_rols(projectname) return render_template("project/user_list.html", users_and_roles=users_and_roles)
def new_project(project: Project, token: HTTPAuthorizationJWT = Depends(http_bearer_scheme)): project.owner = token.github_id project.slug = slugify(project.name) db.insert.project(project) # TODO: set project.id / not needed for ui return project
def create_project(username): user = User.query.filter_by(username=username).first_or_404() form = ProjectForm() if form.validate_on_submit(): if form.picture.data: picture_file = save_project_picture(form.picture.data) project = Project(title=form.title.data, description=form.description.data, image_file=picture_file) db.session.add(project) db.session.commit() else: project = Project(title=form.title.data, description=form.description.data) db.session.add(project) db.session.commit() # I am using advantage of the fact that projects and usesrs are a many-to-many relationship # So here I have to the project creator as a user that is part of this particular project # Further down, I do the same thing when I invite people # This is so we can quickly gather who is part of a project # This is the same logic as with a youtube channel and people subscribed to it project.users_in.append(user) json = {'id': project.id, 'sprint': 1} toAdd = Sprint(project_id=json["id"], sprint_num=json["sprint"]) db.session.add(toAdd) db.session.commit() flash('You have successfully created a new project', 'success') return redirect( url_for('user_projects', username=current_user.username)) return render_template('create_project.html', title='New Project', form=form, legend='New Project')
def add_project(uuid): """Adds new project for given user. Receives - uuid: uuid4 [required - in URL] - start_date: date [required] - end_date: date [optional] - name: string [required] - description: text [optional] - role_id: integer [required] Create a new project associated to uuid and position/role/degree """ content = request.json if not content: abort(400) content['start_date'] = pl.convert_to_date(content['start_date']) project = Project(**content) project.uuid = uuid pl.convert_to_date(project.start_date).date() # pl.convert_to_date(project.end_date).date() try: db.session.add(project) db.session.commit() return "Project added" except: abort(400)
def projectGet(p, d, filename, refresh): # Refresh meta data about the project if needed if refresh: data = { 'prettyname': d['name'], 'website': d['website'], 'handler': d['handler']['type'] } data = json.dumps(data, separators=(',', ':')) pm = Project.gql('WHERE project = :1', p).get() if pm: pm.data = data else: pm = Project(project=p, data=data) pm.put() # Get version info with specified handler handler = d['handler']['type'] handlerargs = d['handler'] h = testHandler(handler) if h[0]: version = h[1](p, handlerargs) logging.info('current version: ' + version) # Cache version for an hour memcache.set('version:' + p, version, 3600) else: logging.error('invalid Handler!')
def db_init(drop): """ Initialize the database of the Flask application. Create the tables, and fill some basic data. :return: None. """ if drop: click.confirm('This operation will delete the database, do you want to continue?', abort=True) click.echo('Dropping tables...') db.drop_all() click.echo('Dropped.') click.echo('Creating database...') db.create_all() click.echo('Created.') click.echo('Filling basic data...') # Data for class Gender(). db.session.add_all([ Gender(name='Unknown', name_zh='未知'), Gender(name='Male', name_zh='男性'), Gender(name='Female', name_zh='女性'), ]) # Data for class Company(). db.session.add_all([ Project(name='南京2016G61地块项目', code='海珀'), Project(name='南京2017G41地块项目', code='海悦'), ]) click.echo('Filled.') click.echo('Committing...') db.session.commit() click.echo('Commit succeed.')
def test_project_delete_cascade_option(self): p1 = Project(name="Project 1") p2 = Project(name="Project 2") p1ct1 = ConfigTemplate(name="first", project=p1) p1ct2 = ConfigTemplate(name="second", project=p1) p2ct1 = ConfigTemplate(name="first", project=p2) db.session.add_all([p1, p2, p1ct1, p1ct2, p2ct1]) db.session.commit() # test sums in DB self.assertTrue(len(Project.query.all()) == 2) self.assertTrue(len(ConfigTemplate.query.all()) == 3) # delete objects db.session.delete(p1ct1) self.assertTrue(len(Project.query.all()) == 2) self.assertTrue(len(ConfigTemplate.query.all()) == 2) db.session.delete(p1) self.assertTrue(len(Project.query.all()) == 1) self.assertTrue(len(ConfigTemplate.query.all()) == 1) db.session.delete(p2) self.assertTrue(len(Project.query.all()) == 0) self.assertTrue(len(ConfigTemplate.query.all()) == 0)
def setUpClass(cls): cls.session = None User.destroy_all() supervisor = User(username=HttpApiTestCase.SUPERVISOR["username"], supervisor=True, password_raw=HttpApiTestCase.SUPERVISOR["password"]) supervisor.save() user = User(username=HttpApiTestCase.GENERAL_USER["username"], supervisor=False, password_raw=HttpApiTestCase.GENERAL_USER["password"]) user.save() supertoken = supervisor.get_auth_token() usertoken = user.get_auth_token() cls.supervisor = supervisor cls.supertoken = supertoken.token cls.user = user cls.usertoken = usertoken.token cls.project1 = Project(name="Test Project 1", owner_id=supervisor._id) cls.project1.save() cls.project2 = Project(name="Test Project 2", owner_id=user._id) cls.project2.save()
def project_edit(project_id=None): method = request.method project_id = project_id.strip() if (method == "POST"): form = request.form project_no = form.get("project_no", "") project_name = form.get("project_name", "") repo_type = form.get("repo_type", "git") repo_url = form.get("repo_url") status = form.get("status", "on") deploy_from = form.get("deploy_from", "") exclude = form.get("exclude", "") release_user = form.get("release_user", "") deploy_to = form.get("deploy_to", "") release_to = form.get("release_to", "") review = form.get("review", "") model = Project() if (project_id is None or project_id == ""): query_project = Project.query.filter_by(id=project_id).first() if (query_project is not None): model = query_project() for item in form: item_val = form.get(item, "") if (hasattr(model, item)): model.__setattr__(item, item_val) DBSession.save(model) return Result("succ", 0, url_for(".project_list")).getIframeResponse() else: return render_template("project/edit.html", project_id=None)
def test_create_project(self): # create test data p1 = Project(name="First Test Project") p2 = Project(name="Second Test Project") # add data to the database db.session.add(p1) db.session.add(p2) self.assertIsNone(p1.id) self.assertIsNone(p2.id) db.session.commit() self.assertIsNotNone(p1.id) self.assertIsNotNone(p2.id) # read all data from the database projects = Project.query.all() received_p1 = projects[0] received_p2 = projects[1] self.assertEqual(p1, received_p1) self.assertEqual(p2, received_p2) self.assertEqual(p1.id, received_p1.id) self.assertEqual(p2.id, received_p2.id) # read specific data from the database filter_p1 = Project.query.filter_by(name="First Test Project").first() self.assertEqual(filter_p1, p1) # check common methods self.assertEqual(repr(filter_p1), "<Project 'First Test Project'>") # config templates should be empty self.assertEqual(received_p1.configtemplates.all(), []) self.assertEqual(received_p2.configtemplates.all(), [])
def add_projects(num_projects=20): designations = [d['name'] for d in Designation.get_all()] categories = [c['name'] for c in Category.get_all()] year = [y['requirement_name'] for y in Requirement.get_all_year(include_none=True)] major = [m['requirement_name'] for m in Requirement.get_all_major(include_none=True)] department = [d['requirement_name'] for d in Requirement.get_all_department(include_none=True)] for i in xrange(num_projects): name = 'Project #{}'.format(i) description = 'Description for {}'.format(name) advisor_name = 'Advisor for {}'.format(name) advisor_email = 'project{}[email protected]'.format(i) est_num_students = randint(0, 1000) designation = designations[randint(0, len(designations) - 1)] cats = [categories[i] for i in sample(xrange(len(categories)), randint(2, 5))] reqs = [] if choice([True, False]): reqs.append(year[randint(0, len(year) - 1)]) if choice([True, False]): reqs.append(major[randint(0, len(major) - 1)]) else: reqs.append(major[randint(0, len(department) - 1)]) new_project = Project( name=name, description=description, advisor_name=advisor_name, advisor_email=advisor_email, est_num_students=est_num_students, designation_name=designation, categories=cats, requirements=reqs, is_new_project=True ) new_project.save()
def setUp(self): # 创建数据库和表 mongodb_url = os.getenv('MONGODB_URL') mongo_client = MongoClient(mongodb_url) if 'test' not in mongo_client.list_database_names(): db = mongo_client['test'] foo_collection = db['foo'] foo_collection.insert_one({'message': 'db created'}) else: mongo_client.drop_database('test') db = mongo_client['test'] foo_collection = db['foo'] foo_collection.insert_one({'message': 'db created'}) self.mongo_client = mongo_client self.mongo = PyMongo(app, uri=f'{mongodb_url}/test') # 创建一个用户user user = User(user_name='mql', passwd_hash='python', mongo=self.mongo) user.save() # 添加项目 proj = Project('mqlabc/learngit', project_url='https://github.com/mqlabc/learngit', mongo=self.mongo, owners_list=['mql', 'lml']) proj.save() # 创建另一个用户user1 user1 = User(user_name='lml', passwd_hash='python', mongo=self.mongo) user1.save() self.client = app.test_client() # 创建测试客户端 self.runner = app.test_cli_runner() # 创建测试命令运行器 app.config.update(TESTING=True, mongo=self.mongo)
def project_create_update(params, project_id): if isinstance(project_id, int): project = Project.query.get(project_id) else: project = Project() print('project_id', project_id) print('POST: ') # project = Project() fields = [] for param in params: field = request.form.get(param, None) if not field: field = None fields.append(field) if all(f is None for f in fields): pass else: # https://stackoverflow.com/questions/3253966/python-string-to-attribute project.project_title = fields[0] project.year_1 = fields[1] project.year_2 = fields[2] project.year_3 = fields[3] project.year_4 = fields[4] project.year_5 = fields[5] project.justification = fields[6] project.comments = fields[7] if isinstance(project_id, int): db.session.commit() else: db.session.add(project) db.session.commit()
def seed_projects(): data = [ Project( name='Anyone Seen The Light?', engineerId=1, artistId=3, artwork='https://f4.bcbits.com/img/a2841769959_10.jpg'), # noqa Project( name='Brain Gravy', engineerId=1, artistId=3, artwork= 'https://image.spreadshirtmedia.com/image-server/v1/compositions/T378A2PA3280PT17X0Y21D1034598672FS6770/views/1,width=500,height=500,appearanceId=2/brain-gravy-eco-friendly-cotton-tote.jpg' ), # noqa Project( name='AT.PLAY', engineerId=1, artistId=4, artwork= 'https://xlr8r.com/wp-content/uploads/2019/06/cover1600x1600.jpg' ), # noqa ] for project in data: db.session.add(project) db.session.commit()
def post(self): # 创建项目 data = request.get_json() name = data['p_name'] desc = data['p_desc'] if name == '': return jsonify({'msg': '项目名不能为空', 'code': 101}) # 查询数据库判断是否项目已存在 db_project = Project.query.filter_by(p_name=name, status=True).first() if db_project: return jsonify({'msg': '项目名已存在', 'code': 400}) userId = get_jwt_identity() new_project = Project(p_name=name, p_desc=desc, creator=userId) try: new_project.create() return jsonify({"code": 201, "msg": "创建项目成功"}) except Exception as e: db.session.rollback() return jsonify({"code": 400, "msg": e}) finally: db.session.close()
def test_projects__2(app_server_db): project_1 = Project(project_name='project_1') app_server_db.session.add(project_1) app_server_db.session.commit() project_2 = Project(project_name='project_2') app_server_db.session.add(project_2) app_server_db.session.commit() r = requests.get(url=rest_url + '/projects/1') assert r.status_code == 200 r_project = r.json() print(r_project) assert r_project['project_name'] == project_1.project_name r = requests.get(url=rest_url + '/projects/2') assert r.status_code == 200 r_project = r.json() print(r_project) assert r_project['project_name'] == project_2.project_name # will the results always be in sorted order according to project_id? r = requests.get(url=rest_url + '/projects/') assert r.status_code == 200 r_projects = r.json() print(r_projects) assert len(r_projects) == 2 assert r_projects[0]['project_name'] == project_1.project_name assert r_projects[1]['project_name'] == project_2.project_name
def create_project(): form = CreateProjectForm() if form.validate_on_submit(): project = Project(form.name.data, form.description.data) project.save() return redirect(url_for("user.profile", user=user)) return render_template("user/create_project.html", form=form)
def advisors_new_project(): try: data = request.get_json(force=True) print(request.headers.get('Content-Type')) print(data) print(request.get_json()) if data is None: return jsonify({'error': 'Request JSON was not found'}), Status.BAD required_fields = ['title', 'description', 'location', 'duration', \ 'budget', 'specialtyId', 'occupationId', 'requiredQualifications', \ 'preferredQualifications', 'startDate', 'advisorWhoPostedId', 'referralFee'] for r_field in required_fields: if data.get(r_field, None) is None: return jsonify({'error': r_field + ' was not given'}), Status.BAD new_proj = Project() new_proj.title = data.get('title', '') new_proj.description = data.get('description', '') new_proj.location = data.get('location', '') new_proj.duration = data.get('duration', 0.0) new_proj.budget = data.get('budget', 0.0) #new_proj.project_image_url = data.get('projectImageUrl', '') #new_proj.file_attachments = data.get('fileAttachments', []) specialty = data.get('specialtyId') #new_proj.specialty_id = db.session.query(Specialty).filter_by(name = specialty).first().pk_id occupation = data.get('occupationId') #new_proj.occupation_id = db.session.query(Occupation).filter_by(name = occupation).first().pk_id #new_proj.preferred_previous_bigfirm_id = data.get('preferredPrevBigFirmId', None) #new_proj.status = data.get('status', '') #new_proj.required_years_experience = data.get('requiredYearsExp', 0) #new_proj.requested new_proj.required_qualifications = data.get('requiredQualifications', '') new_proj.preferred_qualifications = data.get('preferredQualifications', '') new_proj.start_date = data.get('startDate', None) db.session.add(new_proj) if new_proj not in db.session: db.session.rollback() db.session.close() return jsonify({'error': "Couldn't insert project successfully" }), Status.BAD else: db.session.commit() return jsonify({}), Status.COMPLETED except: db.session.rollback() db.session.close() e = sys.exc_info()[0] v = sys.exc_info()[1] print(str(e)) print(str(v)) return jsonify({'error': str(e), 'value': str(v)}), Status.BAD
def upload_project(): session = db.session prj = open('xls/progetti.csv', encoding='utf-8-sig') for line in prj: row = Project(project=line) row.created_by_fk = '1' row.changed_by_fk = '1' session.add(row) session.commit()
def seed_projects(): project1 = Project(title='Test Project', completed=False, userId=2) db.session.add(project1) project2 = Project(title='Test Project 2', completed=False, userId=1) db.session.add(project2) db.session.commit()
def post(self): args = parser.parse_args() p = Project() p.contact_id = args['project_contact_id'] p.name = args['project_name'] p.notes = args['project_notes'] db.session.add(p) db.session.commit() return p , 201
def test_association_proxies(self): user = User() project = Project() user.projects = [project] project.users = [user] user.save() project.save()
def create_project(): project_json = get_project_json() project = Project( data=project_json ) save_project(project) return jsonify(project=project.serialize()), 201
def test_add_project(self): user = User() project = Project() user.save() project.save() assoc_object = user.add_project(project, ProjectsUsers.ROLE_ADMIN, False) assert assoc_object.user == user assert assoc_object.project == project
def make_project(description, lab, team): project=Project(); project.description = description project.lab_id=lab.lab_id db.session.add(project) db.session.flush() #generates pk for new project for student in team: student.project_id = project.project_id db.session.commit() return project
def __init__(self, current_user, sender, page_size=10): self.current_user = current_user self.sender = sender self.page_size = page_size if not self.current_user.current_project: project = Project(name='default', telegram_user=self.current_user) project.save() self.current_user.current_project = project self.current_user.save()
class UserTest(TestCase): def setUp(self): from app.models import User from django.core.files.uploadedfile import SimpleUploadedFile from app.models import Project self.user = User(email='*****@*****.**') self.user_two = User(email='*****@*****.**') self.user.save() self.user_two.save() self.file = SimpleUploadedFile('testimage.jpg', '', content_type='image/jpeg') self.project = Project( description='Description', goal=10000, created_by=self.user, cover_image=self.file, ) self.project.save() def tearDown(self): from kickfarter import settings os.remove(os.path.join(settings.MEDIA_ROOT, self.file.name)) def test_pledging(self): from app.exceptions import BackingException from app.models import Project with self.assertRaises(BackingException) as e: # Pledging on a project that is not active self.user.pledge(100, self.project) self.assertContains(e.msg, 'active projects') self.project.status = Project.STATUS_ACTIVE with self.assertRaises(BackingException) as e: # Pledging to their own project self.user.pledge(100, self.project) self.assertContains(e.msg, 'own projects') pledge = self.user_two.pledge(100, self.project) self.assertEqual(100, pledge.amount) self.assertEqual(self.project, pledge.project) self.assertEqual(self.user_two, pledge.user) self.assertEqual(self.user_two.pledged_to.first(), self.project) self.assertEqual(self.user_two.pledges.first(), pledge) with self.assertRaises(BackingException) as e: # Pledging again self.user.pledge(100, self.project) self.assertContains(e.msg, 'already backed')
def test_user_project_membership(self): u1 = User(username="******", email="*****@*****.**") u1.set_password("test_pass") p1 = Project(name="project #1", description="test project #1") db.session.add_all([u1, p1]) db.session.commit() self.assertFalse(u1.is_in_project(p1)) p1.add_to_project(u1) db.session.commit() self.assertTrue(u1.is_in_project(p1))
def make_project(description, lab, student1, student2): project = Project() project.description = description project.lab_id = lab.lab_id db.session.add(project) db.session.flush() #generates pk for new project student1.project_id = project.project_id if student2 is not None: student2.project_id = project.project_id db.session.commit() return project
def projects(): # (WIP) Pagination if current_user.is_authenticated: projects = Project.get_projects(id=current_user.id) else: projects = Project.get_projects() form = RequestProjectAccessForm() return render_template("projects/projects.html", title="Projects", projects=projects, form=form)
def test_unique_constrain_of_the_project_name(self): # create test data p1 = Project(name="First Test Project") p2_with_same_name = Project(name="First Test Project") db.session.add(p1) db.session.add(p2_with_same_name) # integrity error is thrown if the changes should be commited with self.assertRaises(IntegrityError): db.session.commit()
def new_project(): form = NewComponentForm() if form.validate_on_submit(): project = Project(name=form.name.data, description=form.description.data) db.session.add(project) project.add_to_project(current_user) db.session.commit() flash("Project - \"{}\" created successfully!".format(project.name)) return redirect(url_for('main.index')) return render_template('main/new_project.html', form=form)
def test_model_structure_file(self): """Test to make sure that StructureFile is working properly. """ structure_file1 = StructureFile(path="foo") structure_file2 = StructureFile(path="bar") project = Project() project.structure_files = [structure_file1, structure_file2] project.save() assert Project.query.all()[0].structure_files == [structure_file1, structure_file2]
def addProject(): """Add a portfolio project""" form = ProjectForm() if form.validate_on_submit(): project = Project() project.owner = current_user form.populate_obj(project) project.slug = project.title.lower() db.session.add(project) db.session.commit() return redirect(url_for('portfolio.home')) return render_template('portfolio/compose.html', form=form)
def uploadRegistered(request): """Upload and save the zip""" if request.user.is_authenticated(): user = request.user.username else: return HttpResponseRedirect('/') if request.method == 'POST': form = UploadFileForm(request.POST) # Analyze the scratch project and save in our server files fileName = handle_uploaded_file(request.FILES['zipFile']) # Analize project and to save in database the metrics d = analyzeProject(request,fileName) fupdate = datetime.now() # Get the short name shortName = fileName.split('/')[-1] # Get the dashboard of user myDashboard = Dashboard.objects.get(user=user) # Save the project newProject = Project(name=shortName, version=1, score=0, path=fileName, fupdate=fupdate, dashboard=myDashboard) newProject.save() # Save the metrics dmaster = d["mastery"] newMastery = Mastery(myproject=newProject, abstraction=dmaster["Abstraction"], paralel=dmaster["Parallelization"], logic=dmaster["Logic"], synchronization=dmaster["Synchronization"], flowcontrol=dmaster["FlowControl"], interactivity=dmaster["UserInteractivity"], representation=dmaster["DataRepresentation"], TotalPoints=dmaster["TotalPoints"]) newMastery.save() newProject.score = dmaster["Total{% if forloop.counter0|divisibleby:1 %}<tr>{% endif %}Points"] if newProject.score > 15: newProject.level = "advanced" elif newProject.score > 7: newProject.level = "developing" else: newProject.level = "beginner" newProject.save() for charx, dmetrics in d["attribute"].items(): if charx != 'stage': newAttribute = Attribute(myproject=newProject, character=charx, orientation=dmetrics["orientation"], position=dmetrics["position"], costume=dmetrics["costume"], visibility=dmetrics["visibility"], size=dmetrics["size"]) newAttribute.save() iterator = 0 for deadx in d["dead"]: if (iterator % 2) == 0: newDead = Dead(myproject=newProject, character=deadx, blocks=0) else: newDead.blocks = deadx newDead.save() iterator += 1 newDuplicate = Duplicate(myproject=newProject, numduplicates=d["duplicate"][0]) newDuplicate.save() for charx in d["sprite"]: newSprite = Sprite(myproject=newProject, character=charx) newSprite.save() return HttpResponseRedirect('/myprojects')
def projectsList(): ps = Project.all() projects = [] for project in ps: projects.append(project.project) projects.sort() return projects
def getProjectMeta(project): p = memcache.get('version:' + project + ':meta') if not p: pd = Project.all().filter('project = ', project).get() p = json.loads(pd.data) memcache.set('version:' + project + ':meta', p, 600) return p
def post(self): ctx = self.get_context() form = ctx['form'] if form.validate(): project = Project() form.populate_obj(project) project.users = User.objects.all() # for now, all users are on the projects # Check that repo exists and that the user can access it. if project.repo: if not project.author.github_access: return redirect(url_for('github_login')) if not project.ping_repo(): flash('The repo <b>%s</b> doesn\'t seem to exist!' % project.repo) form.repo.errors = ['Can\'t access this repo.'] return render_template('project/new.html', form=form) # Create a Google Drive Folder for this project on its authors account. project.create_folder() project.save() flash('The <b>%s</b> project was successfully summoned.' % project.name) return redirect(url_for('project_api', slug=project.slug, _method='GET')) flash('You have forgotten something. Without your guidance, we are lost.') return render_template('project/new.html', form=form)
def test_add_sequence(self): """Test the ``add_sequence()`` method of ``Sentence``. """ sentence = Sentence(text="foo") sequence = Sequence(lemmatized=False) project = Project() project.save() sentence.save() sequence.save() rel = sentence.add_sequence(sequence, position=1, project=project) assert rel.sequence == sequence assert rel.sentence == sentence assert rel.position == 1 assert rel.project == project
def post(self): parsed = parser.parse_args() # user_id = db.session.query(User).filter(User.id == g.user['id']).first() task = Task(name=parsed['name'], description=parsed['description'], project_id=parsed['project_id']) project_tasks = Project.tasks(parsed['project_id'], task.id) db.session.add(project_tasks) db.session.add(task) db.session.commit() return task, 201
def test_document_belongs_to(self): """Check if ``belongs_to()`` on ``Document`` is working properly. """ user = User() project = Project() document_file = DocumentFile() document = Document() project.document_files = [document_file] document_file.documents = [document] user.projects = [project] user.save() project.save() document.save() document_file.save() assert document.belongs_to(user)
def refreshProjectCache(name, sha): # Delete old Project models for the project if they exists for p in Project.gql("WHERE project = :1", name): p.delete() # Delete old ShaCache models for the project if they exists for s in ShaCache.gql("WHERE project = :1", name): s.delete() # Fetch new data, loads and dumps json to remove newlines from the input. (multiline not ok in datastore) data = json.dumps(json.loads(urlfetch.fetch(rawPath(name)).content), separators=(',', ':')) # Put new project data into a Project Model p = Project(project=name, data=data) p.put() # Put new sha hash into a ShaCache Model s = ShaCache(project=name, sha=sha) s.put()
def test_get_documents(self): """Test the get_documents method. """ document_file1 = DocumentFile() document_file2 = DocumentFile() document1 = Document() document2 = Document() document3 = Document() project = Project() document_file1.documents = [document1, document2] document_file2.documents = [document3] project.document_files = [document_file1, document_file2] project.save() assert project.get_documents() == [document1, document2, document3]
def getProjectsList(): p = memcache.get('projectsList') if not p: ps = Project.all() p = [] for project in ps: p.append(project.project) p.sort() memcache.set('projectsList', p, 600) return p
def test_add_word(self): """Test the ``add_word()`` method of ``Sentence``. """ sentence = Sentence(text="foo") word = Word(word="foo") project = Project() project.save() sentence.save() word.save() rel = sentence.add_word(word, position=4, space_before=" ", part_of_speech="ADF", project=project) assert rel.word == word assert rel.sentence == sentence assert rel.position == 4 assert rel.space_before == " " assert rel.part_of_speech == "ADF" assert rel.project == project
def test_logs(self): """Test that logs work right. """ project = Project() info_logs = [InfoLog(item_value="foo", log_item="foo is", project=project), InfoLog(item_value="bar", log_item="Fooing the bar", project=project), InfoLog(item_value="foo", log_item="Still fooing", project=project)] error_logs = [ErrorLog(item_value="F", log_item="Bar", project=project), ErrorLog(item_value="Failed to foo", log_item="bar", project=project)] warning_logs = [WarningLog(item_value="W", log_item="bar", project=project)] project.save() assert project.get_infos() == info_logs assert project.get_errors() == error_logs assert project.get_warnings() == warning_logs
def test_add_dependency(self): """Test the ``add_dependency()`` method of ``Sentence``. """ sentence = Sentence(text="foo") word = Word(word="foo") dependency = Dependency(governor=word) project = Project() project.save() sentence.save() dependency.save() word.save() rel = sentence.add_dependency(dependency, governor_index=1, dependent_index=2, project=project) assert rel.dependency == dependency assert rel.sentence == sentence assert rel.governor_index == 1 assert rel.dependent_index == 2 assert rel.project == project
def projectsListDetailed(): ps = projectsList() projects = [] for project in ps: p = Project.all().filter('project = ', project).get() data = json.loads(p.data) if data['meta']['prettyname']: prettyname = data['meta']['prettyname'] else: prettyname = project projects.append((prettyname, project)) return projects
def add_project(): """add a new Project :return: """ form = ProjectForm(request.form) if form.validate_on_submit(): try: project = Project(name="") project.name = form.name.data db.session.add(project) db.session.commit() flash("Project <strong>%s</strong> successful created" % project.name, "success") return redirect(url_for("view_project", project_id=project.id)) except IntegrityError as ex: if "UNIQUE constraint failed" in str(ex): msg = "Project name already in use, please use another one" else: msg = "Project was not created (unknown error, see log for details)" flash(msg, "error") logger.error(msg, exc_info=True) db.session.rollback() except Exception: msg = "Project was not created (unknown error, see log for details)" logger.error(msg, exc_info=True) flash(msg, "error") db.session.rollback() return render_template("project/add_project.html", form=form)
def _projects_from_json(app, content=''): if 'projects' in content: for obj in content['projects']: user = User.query.filter_by(email=obj['user']).first() if user is None: app.logger.error('Project: %s, Unknown user: %s' % (obj['name'], obj['user'])) break company = Company.query.filter_by(user=user, name=obj['company']).first() if company is None: app.logger.error('Project: %s, Unknown company: %s' % (obj['name'], obj['company'])) break project = Project.query.filter_by(user=user, company=company, name=obj['name']).first() if project is None: project = Project() project.user = user project.company = company project.name = obj['name'] project.description = obj['description'] app.logger.debug('adding project: %s' % project) db.session.add(project) db.session.commit()
def get (self,project_name): project = Project.get_by_key_name('name='+project_name) source_files = SourceFile.all().filter('project =',project) path = [project_name] f = SolutionRenderer() templates = process_template_imems() process_template_path(templates, path) templates.update({ 'files': source_files, 'projects': projects, 'path': path, 'project': project_name }) return self.response.write(f.render('project',templates))
def get(self,project_name): print repr(project_name) project = Project.get_by_key_name('name='+project_name) source_files = SourceFile.all().filter('project =',project) for file in source_files: print file # print "source_files",source_files files = map(lambda x: {'name':x.name,'size':int(x.p*100)}, source_files) # print 'files',files files = make_nodes_hier(files, project_name) result = json.dumps(files) print "result",result # print 'node_arch',files self.response.headers['Content-Type'.encode()] = 'application/json'.encode() self.response.out.write(result)
def save_project(request): user_id = request.session['user_id'] if not user_id: return HttpResponse("not logged") name = request.POST.get('name') project = Project.objects.filter(name=name, status='active') if project: return HttpResponse("duplicate") else: project = Project() project.name = name project.description = request.POST.get('description') project.status = 'active' project.created_by = request.session['user_id'] project.created_at = time.strftime('%Y-%m-%d %H:%M:%S') project.save() return HttpResponse('done')
def __init__(self, project_files, project_name): print project_name if not isinstance(project_files, dict): raise TypeError ("project_files have to be dict") if not isinstance(project_name, str): raise TypeError("project_name must to be str") # try: if project_files['error'] == False: if isinstance (project_files['project'], (list)): # list of files self.project_files = project_files['project'] self.project_name = project_name self.project = Project.get_or_insert('name='+self.project_name) self.project.name = self.project_name self.project.short = md5(project_name).hexdigest() self.init_sources_for_extrapolation() self.files = [] self.process_sources() self.project.put() else: raise SourceFilesFormatError else: raise SourceFilesFormatError
def loadProjectData(name): p = Project.gql("WHERE project = :1", name).get() return json.loads(p.data)
def index(): return render_template('index.html', title="Homepage", user=current_user, projects=Project.get_all())
def create_project(): p = Project.create(name="Test Project") return p
username="******", new_role="mentor", expertise="hardware hacking, painting, entrepreneurship", linkedin_id="highstatus", interests="Arduino, Flying Machines, Service projects", password_hash=password_hash, confirmed=True) db.session.add(one) db.session.add(two) db.session.add(three) db.session.commit() User.generate_fake() Post.generate_fake() Project.generate_fake() for post in Post.query.filter_by(author=None): db.session.delete(post) subjects =['mathematics', 'science', 'engineering', 'literature', 'music', \ 'service', 'entrepreneurship', 'art', 'public-service', 'creative-writing'] length = len(subjects) projects = [] all_students = User.query.filter_by(new_role="student").all() for i in range(20): name = 'Project' + str(i)