def modify_resource(): if 'resource_ids' not in session: session['resource_ids'] = db_handler.get_resource_ids() # POST if request.method == 'POST': # Load Resource if request.form.get('res_sel'): session['resource'] = Resource(request.form['res_sel']).serialize() # Modify keys else: resource = decode(session['resource']) mod_keys = list() for key in resource.keys: mod_key = dict(KEY_ID=key['KEY_ID'], KEY_NAAM=key['KEY_NAAM'] , KEY_GELDIG=int(request.form[key['KEY_NAAM']])) mod_keys.append(mod_key) resource.update_keys(mod_keys) session['resource'] = resource.serialize() # GET else: if 'resource' not in session: session['resource'] = Resource(session['resource_ids'][0]).serialize() return render_template('modify_resource.html' , resource=decode(session['resource']) , resource_ids=session['resource_ids'] , choices=VALID_KEYS_VALS)
def test_resource(): resource = Resource(name='name', url='https://resource.url', category=Category(name='Category'), languages=[Language(name='language')], free=False, notes='Some notes') assert (resource.key() == 'https://resource.url') assert (resource.__hash__() == hash('https://resource.url')) assert (resource.__repr__() == "<Resource \n" "\tName: name\n" "\tLanguages: [<Language language>]\n" "\tCategory: <Category Category>\n" "\tURL: https://resource.url\n>") assert (resource.serialize() == { 'id': None, 'name': 'name', 'url': 'https://resource.url', 'category': 'Category', 'languages': ['language'], 'free': False, 'notes': 'Some notes', 'upvotes': None, 'downvotes': None, 'times_clicked': None, 'created_at': '', 'last_updated': '', 'user_vote_direction': None }) # Test equality resource_copy = resource assert (resource == resource_copy) not_copy = Resource(name='different name') assert (resource != not_copy) not_copy.name = 'name' not_copy.url = 'https://notresource.url' assert (resource != not_copy) not_copy.url = 'https://resource.url' assert (resource != not_copy) not_copy.free = True assert (resource != not_copy) not_copy.free = False not_copy.notes = 'Some other notes' assert (resource != not_copy) not_copy.notes = 'Some notes' not_copy.category = 'Different Category' assert (resource != not_copy) not_copy.category = Category(name='Category') not_copy.languages = ["different language"] assert (resource != not_copy) not_copy.languages = [Language(name='language')] assert (resource == not_copy) assert (resource != 1)
def resource_map(): if 'resource_ids' not in session: session['resource_ids'] = db_handler.get_resource_ids() if request.method == 'POST': session['resource'] = Resource(request.form['res_sel']).serialize() else: if 'resource' not in session: session['resource'] = Resource(session['resource_ids'][0]).serialize() return render_template('resource_map.html', resource_ids=session['resource_ids'], resource=decode(session['resource']))
def issue(): form = ResIssueForm() if form.validate_on_submit(): resfile = form.resfile.data filename = resfile.filename res = Resource( title=form.title.data, price=form.price.data, body=form.body.data, issuer=current_user, filename=filename ) db.session.add(res) db.session.commit() filedir = os.path.join(app.config['RES_FILE_PATH'], str(res.id)) if not pathlib.Path(filedir).exists(): os.makedirs(filedir) resfile.save( os.path.join( app.config['RES_FILE_PATH'], str(res.id), res.filename ) ) flash('1,发布成功!!!资源已上架!') return redirect(url_for('index')) return render_template('issue/res.html', title="issue resource", form=form)
def create_resources(): try: req = request.get_json(force=True) if req["data"] != "": data = req["data"] else: data = req except Exception: data = request.get_data().decode("utf-8") data = data.split("|") data = { "name": data[0], "parent_name": data[1], "instance_type": data[2], "imported_at": data[3] } if 'name' not in data or 'parent_name' not in data or 'imported_at' not in data: return bad_request( 'must include name, parent_name, instance_type and imported_at') resource = Resource() resource.from_dict(data, new_data=True) db.session.add(resource) db.session.commit() response = {"isSucceed": True, "resource": resource.to_dict()} response = jsonify(response) response.headers['Location'] = url_for('api.get_resource_by_id', id=resource.id) return response
def _insert_resources(level_resources: List = None) -> None: """ insert resources to database """ insert_resources_code = [ level_resource.get('code') for level_resource in level_resources ] query_resources = db.session.query(Resource.code, Resource).all() query_resources_dict = dict(query_resources) query_resources_code = query_resources_dict.keys() insert_code = set(insert_resources_code) ^ set(query_resources_code) update_code = set(insert_resources_code) & set(query_resources_code) for level_resource in level_resources: level_code = level_resource.get('code') if level_code in insert_code: resource = Resource() for key, value in level_resource.items(): if hasattr(resource, key): setattr(resource, key, value) db.session.add(resource) elif level_code in update_code and query_resources_dict.get(level_code): query_resource = query_resources_dict.get(level_code) for key, value in level_resource.items(): if hasattr(query_resource, key): setattr(query_resource, key, value) else: raise RuntimeError(f'Please check {level_resource}') db.session.commit()
def create_resources(json, db): try: # Resources to return in the response created_resources = [] # Serialized Resources to send to Algolia created_resources_algolia = [] # Resource IDs to delete if Algolia fails to index resource_id_cache = [] # Create each Resource in the database one by one for resource in json: langs, categ = get_attributes(resource) new_resource = Resource( name=resource.get('name'), url=resource.get('url'), category=categ, languages=langs, paid=resource.get('paid'), notes=resource.get('notes')) try: db.session.add(new_resource) db.session.commit() created_resources_algolia.append(new_resource.serialize_algolia_search) resource_id_cache.append(new_resource.id) except IntegrityError as e: logger.exception(e) return utils.standardize_response(status_code=422) except Exception as e: logger.exception(e) return utils.standardize_response(status_code=500) created_resources.append(new_resource.serialize) # Take all the created resources and save them in Algolia with one API call try: index.save_objects(created_resources_algolia) except (AlgoliaUnreachableHostException, AlgoliaException) as e: if (environ.get("FLASK_ENV") != 'development'): logger.exception(e) # Remove created resources from the db to stay in sync with Algolia for res_id in resource_id_cache: res = Resource.query.get(res_id) res.languages.clear() db.session.delete(res) db.session.commit() msg = "Algolia failed to index resources" error = {'errors': [{"algolia-failed": {"message": msg}}]} return utils.standardize_response(payload=error, status_code=500) # Success return utils.standardize_response(payload=dict(data=created_resources)) except Exception as e: logger.exception(e) return utils.standardize_response(status_code=500)
def add_url(): new_url = request.form['new_url'] new_title = request.form['new_title'] new_resource = Resource(url=new_url, title=new_title) db.session.add(new_resource) db.session.commit() return redirect('/further_resources')
def test_vote_information(): test_apikey = '1234abcd' test_id = 1 test_direction = 'upvote' resource = Resource(id=test_id, name='name', url='https://resource.url', category=Category(name='Category'), languages=[Language(name='language')], paid=False, notes='Some notes') key = Key(email="*****@*****.**", apikey=test_apikey) vote_info = VoteInformation(voter_apikey=key.apikey, resource_id=resource.id, current_direction=test_direction) vote_info.voter = key resource.voters.append(vote_info) assert (vote_info.voter_apikey == test_apikey) assert (vote_info.resource_id == test_id) assert (vote_info.current_direction == test_direction) assert (vote_info.voter == key) assert (vote_info.resource == resource)
def create_resource(json, db): langs, categ = get_attributes(json) new_resource = Resource(name=json.get('name'), url=json.get('url'), category=categ, languages=langs, paid=json.get('paid'), notes=json.get('notes')) try: db.session.add(new_resource) db.session.commit() index.save_object(new_resource.serialize_algolia_search) except (AlgoliaUnreachableHostException, AlgoliaException) as e: logger.exception(e) print(f"Algolia failed to index new resource '{new_resource.name}'") except IntegrityError as e: logger.exception(e) return utils.standardize_response(status_code=422) except Exception as e: logger.exception(e) return utils.standardize_response(status_code=500) return utils.standardize_response(payload=dict( data=new_resource.serialize))
def test_edit_suggestion(self): """Test suggestion of an edit""" r = Resource(name='test_edit') db.session.add(r) try: db.session.commit() except IntegrityError: db.session.rollback() r_added = Resource.query.filter_by(name='test_edit').first() s_text = "The phone number of this establishment is incorrect: it should be 212-346-5927" s_contact_name = "Anonymous Helper" s_contact_email = "*****@*****.**" s_contact_number = "000-001-0101" s_timestamp = datetime.now(pytz.timezone('US/Eastern')) suggestion = Suggestion(resource_id=r_added.id, suggestion_text=s_text, read=1, contact_name=s_contact_name, contact_email=s_contact_email, contact_phone_number=s_contact_number, submission_time=s_timestamp) db.session.add(suggestion) db.session.commit() r_in_table = Suggestion.query.filter_by(suggestion_text=s_text).first() self.assertTrue(r_in_table is not None) self.assertTrue(r_in_table.suggestion_text == s_text) self.assertTrue(r_in_table.resource_id == r_added.id) self.assertTrue(r_in_table.read == 1) self.assertTrue(r_in_table.contact_phone_number == s_contact_number) self.assertTrue(r_in_table.submission_time is not None) self.assertTrue(r_in_table.contact_name == s_contact_name) self.assertTrue(r_in_table.contact_email == s_contact_email)
def create_resource(): form = CreateResourceForm() if form.validate_on_submit(): print(form) print(form.name.data) print(form.description.data) resource = Resource( name=form.name.data, description=form.description.data, user_id=current_user.id, ) try: db.session.add(resource) db.session.commit() flash("Resource added.") except: flash("error adding resource. :(") return redirect(url_for("main.list_resources")) elif request.method == "GET": # load editing data into form pass return render_template( "create_resource.html", title="Add a bookable resource", form=form )
def edit_resource(resource_id): """ Validate the resource Id. Also check for the data in the json payload. If the data exists update the resource with the new data. :param resource_id: resource Id :return: Http Json response """ if request.content_type == 'application/json': data = request.get_json().get("resource") link = data.get('link') if data.get('link') is not None else None categories = data.get('categories') if data.get( 'categories') is not None else None status = data.get('status') if data.get('status') is not None else None updated_resource = Resource(link, categories, status) if link or categories or status: try: int(resource_id) except ValueError: return response('failed', 'Please provide a valid resource Id', 400) resource = Resource.query.filter_by( resource_id=resource_id).first() if resource: resource.update(updated_resource) return response_for_created_resource(resource, 201) return response( 'failed', 'The resource with Id ' + resource_id + ' does not exist', 404) return response( 'failed', 'No attribute or value was specified, nothing was changed', 400) return response('failed', 'Content-type must be json', 202)
def resource_fixture(user: User, topic: Topic, session: Session) -> Resource: resource = Resource(name="UNSW", url="unsw.edu.au", user_id=user.id, topics=[topic]) session.add(resource) session.commit() yield resource
def test_get_resources(self): resource = Resource(resource_name="booking") db.session.add(resource) db.session.commit() response = self.client.get("resource") data = json.loads(response.data) return self.assertEquals(data.get("count"), 1)
def resource(uid): """ Get, add, update, or delete a specific resource based on request method. Modifies database. :param uid: skipper_uid of the resource :return: (str) brief message of action taken """ if request.method == "GET": resource = db.session.query(Resource).filter( Resource.uid == uid).first() return jsonify(data=row_to_dict(resource)) elif request.method == 'DELETE': # Removes resource with given uid, all descendants, and associated edges to_delete = [uid] while len(to_delete) > 0: # delete the resource in question curr_uid = to_delete.pop() db.session.query(Resource).filter( Resource.uid == curr_uid).delete() # find all children outgoing_edges = db.session.query(Edge).filter( Edge.start_uid == curr_uid).all() child_uids = [edge.end_uid for edge in outgoing_edges] to_delete += child_uids # removes edges associated with this resource db.session.query(Edge).filter( Edge.start_uid == curr_uid or Edge.end_uid == curr_uid).delete() db.session.commit() return "Resource, descendants, and associated edges deleted" else: data = request.form.to_dict() # make sure all dates are datetimes if 'created_at' in data.keys() and not isinstance( data['created_at'], datetime.datetime): data['created_at'] = parse(data['created_at']) if request.method == 'POST': # add to db try: r1 = Resource(**data) db.session.add(r1) db.session.commit() except sqlalchemy.exc.IntegrityError: # unique uid already in db requests.put( 'http://127.0.0.1:5000/resource/{}'.format(uid), data=data) # redirect as put request with same data return "Resource saved" if request.method == 'PUT': # update db db.session.query(Resource).filter(Resource.uid == uid).update(data) db.session.commit() return "Resource updated"
def test_res(self): u = User(username='******', email='*****@*****.**') res = Resource(body="hello") res.issuer = u db.session.add(res) db.session.commit() users = User.query.all() self.assertEqual(users[0].resources[0].body, 'hello') self.assertEqual(users[0].resources[0].issuer.username, 'asdf') self.assertEqual(users[0].resources.count(), 1)
def many_resources_fixture(user: User, topic: Topic, session: Session) -> List[Resource]: resources = [ Resource(name="Google", url="google.com", user_id=user.id, topics=[topic]), Resource(name="UNSW", url="unsw.edu.au", user_id=user.id, topics=[]), Resource( name="Introduction To Deep Learning", url="https://sebastianraschka.com/blog/2021/dl-course.html", user_id=user.id, topics=[topic], ), ] for resource in resources: session.add(resource) session.commit() yield resources
def test_filterBy(self): u1 = User(username='******', email='*****@*****.**') res = Resource(body="hello") res.issuer = u1 u2 = User(username='******') res2 = Resource(body='hello u2') res2.issuer = u2 u2.buy_res(res) u3 = User(username='******') db.session.add(u1) db.session.add(res) db.session.add(u3) db.session.commit() u3.obtain_cert( Certs.query.filter_by(resource_id=res.id, payer_id=u2.id, transfer_id=None).first() ) self.assertEqual(Certs.query.get(1).transfer_id, u3.id) certs = Certs.query.filter_by(transfer_id=None) self.assertEqual(certs.count(), 1)
def test_in(self): u1 = User(username='******', email='*****@*****.**') res = Resource(body="hello") res.issuer = u1 u2 = User(username='******') res2 = Resource(body='hello u2') res2.issuer = u2 u2.buy_res(res) db.session.add(u1) db.session.add(res) db.session.commit() ress = Resource.query.filter( ~Resource.payer.any(User.id==u2.id) ).all() # .filter( # Certs.payer_id!=u2.id # ) print(Resource.query.outerjoin(Certs).all()) ress = Resource.query.outerjoin(Certs).all() self.assertTrue((len(ress)==2))
def add_one_resource(self): user = User.query.filter_by(email="*****@*****.**").first() resource = Resource() resource.deserialize({ 'name' : "test_res", 'owner_id' : user.id, 'available_start': "5:00", 'available_end' : "17:00" }) db.session.add(resource) db.session.commit()
def test_create_resource(self): """Test creating a resource with a single option""" r = Resource(name='test') a = OptionAssociation(option=0) options = ['True', 'False'] a.descriptor = Descriptor(name='Open', dtype='option', values=options) r.option_descriptors.append(a) option_assoc = r.option_descriptors[0] self.assertEqual(option_assoc.option, 0) self.assertEqual(option_assoc.descriptor.name, 'Open') self.assertEqual(option_assoc.descriptor.values, options)
def create_resource(json, db): langs, categ = get_attributes(json) new_resource = Resource(name=json.get('name'), url=json.get('url'), category=categ, languages=langs, paid=json.get('paid'), notes=json.get('notes')) db.session.add(new_resource) db.session.commit() return standardize_response(new_resource.serialize, None, "ok")
def test_create_a_resource_missing_key(self): resource = Resource() error = False try: resource.deserialize({ 'name' : "test_res", 'available_start': "5:00", 'available_end' : "17:00" }) except KeyError as e: self.assertTrue("Invalid resource: missing" in e.message) error = True self.assertTrue(error)
def test_buy(self): u1 = User(username='******', email='*****@*****.**') res = Resource(body="hello") res.issuer = u1 u2 = User(username='******') db.session.add(u1) db.session.add(u2) db.session.add(res) db.session.commit() u2.buy_res(res) db.session.commit() self.assertEqual(Certs.query.all()[0].payer_id, 2)
def test_delete(self): u1 = User(username='******', email='*****@*****.**') res = Resource(body="hello") res.issuer = u1 db.session.add(u1) db.session.add(res) db.session.commit() self.assertEqual(u1.id, 1) self.assertEqual(res.id, 1) db.session.delete(u1) # db.session.commit() self.assertTrue(len(User.query.all())==0) self.assertTrue(len(Resource.query.all())==1)
def test_create_a_resource_wrong_value(self): resource = Resource() error = False try: resource.deserialize({ 'name' : "test_res", 'owner_id' : 'not_integer', 'available_start': "5:00", 'available_end' : "17:00" }) except ValueError as e: self.assertTrue("body of request contained bad or no data" in e.message) error = True self.assertTrue(error)
def test_resoperator(self): u1 = User(username='******', email='*****@*****.**') res = Resource(body="hello") res.issuer = u1 u2 = User(username='******') res2 = Resource(body='hello u2') res2.issuer = u2 u2.buy_res(res) u3 = User(username='******') db.session.add(u1) db.session.add(res) db.session.add(u2) db.session.add(res2) db.session.add(u3) db.session.commit() u3.obtain_cert( Certs.query.filter_by(resource_id=res.id, payer_id=u2.id, transfer_id=None).first() ) # query = Resource.query.outerjoin(Certs).filter( # Certs.payer_id==u2.id # ) res_bought = Resource.query.outerjoin(Certs).filter( Certs.payer_id==u2.id ).all() self.assertEqual(len(res_bought), 1) res_bought_ex_trans = Resource.query.outerjoin(Certs).filter( Certs.payer_id==u2.id, Certs.transfer_id==None ).all() self.assertEqual(len(res_bought_ex_trans), 0) res_transfer = Resource.query.join(Certs).filter( Certs.payer_id==u2.id, Certs.transfer_id!=None ).all() self.assertEqual(len(res_transfer), 1)
def add(): form = ResourceForm() if form.validate_on_submit(): resource = Resource(nom=form.nom.data, tipus=form.tipus.data, descripcio=form.descripcio.data, idioma=form.idioma.data, link=form.link.data, author=current_user) db.session.add(resource) db.session.commit() flash(_('S\'ha afegit el nou recurs!')) return redirect(url_for('main.index')) return render_template('add.html', title=_('Home'), form=form, pagetitle=_('Recursos nous'))
def create_resource(json, db): langs, categ = get_attributes(json) new_resource = Resource(name=json.get('name'), url=json.get('url'), category=categ, languages=langs, paid=json.get('paid'), notes=json.get('notes')) try: db.session.add(new_resource) db.session.commit() return standardize_response(payload=dict(data=new_resource.serialize)) except Exception as e: logger.exception(e) return standardize_response(status_code=500)