def done(self): #make sure the profile name doesn't already exist # p = Profile.by_name(self.name) # logging.error("p: %s" % p) # if p: # msg = 'That name already exists.' # self.render('welcome.html', profile = p, user = self.u, countries = countries, error_name = msg) # else: logging.error("En send_profile") profile = loged_profile(self.username) if not profile: logging.error('A guardar profile') p = Profile.save_profile(self.u.name, self.u, self.name, self.profile_type, geo_converter(self.geo_pt), self.phone, self.email, self.street_address, self.address_line_2, self.region, self.city, self.zip_code, self.country, self.web, self.facebook, self.twitter, self.youtube) p.put() else: logging.error('A modificar profile') #logging.error('key:%s' % db.get(profile.key())) p = Profile.update_profile(profile, self.u, self.name, self.profile_type, geo_converter(self.geo_pt), self.phone, self.email, self.street_address, self.address_line_2, self.region, self.city, self.zip_code, self.country, self.web, self.facebook, self.twitter, self.youtube) self.u = loged_user(self.u.name, True) p = loged_profile(self.u.name, True) self.render('ioffer_profile_form_edit.html', profile = p, user = self.u, countries = countries, profile_types = profile_types, last_10_offers = self.get_last_10_offers())
def profile_create(user): user_id = get_jwt_identity() user = User.query.get(user_id) if not user: return abort(401, description="Do I know you?") profile_fields = profile_schema.load(request.json) is_profile = Profile.query.get(user.id) if not is_profile: new_profile = Profile() new_profile.username = profile_fields["username"] new_profile.fname = profile_fields["fname"] new_profile.lname = profile_fields["lname"] user.profile_id.append( new_profile ) # user = defined above; client_id is linked as relationship to user: client_id = db.relationship("Client", backref=backref("users", uselist=False)) in users table db.session.add(new_profile) db.session.commit() #return jsonify(client_schema.dump(new_profile)) return render_template("Profile.html", new_profile=new_profile) else: return abort(401, description='Profile already exists')
def initialize_job(job_dict): # if there are profiles from an unsuccessful initialization, delete them Profile.objects(job_id=str(job_dict["id"])).delete() user_profiles = get_profiles_from_twitter(job_dict["tweepy_api"], job_dict["seed_list"]) profiles = [create_profile_from_dict(job_dict, user_profile) for user_profile in user_profiles] Profile.objects.insert(profiles) # mark as initialized, so that post_job_initialize(str(job_dict["id"]))
def name(self, body: http.Body): """ Searching for a name in the DB. :return: """ payload = json.loads(body.decode()) if payload['name'] is None: return Response({'message': 'The name property is empty'}, status=401) # Get the search text. text = payload['name'] # Init the query operation. profile = Profile() profiles = profile \ .getTable() \ .filter( lambda document: document['name'].match(text) | document['current_position'].match(text) | document['current_title'].match(text) | document['summary'].match(text) ) \ .run(profile.r) # Search in the text in the name, title, position, summary. results = [] for profile in profiles: results.append(profile) return results
def skills(self, body: http.Body): """ Searching for a user in the DB. :return: """ payload = json.loads(body.decode()) if payload['skill'] is None: return Response({'message': 'The skill property is empty'}, status=401) # Get the search text. text = payload['skill'] # Init the query operation. profile = Profile() profiles = profile \ .getTable() \ .filter( lambda document: document['skills'].contains(lambda skills: skills['skill'].match(text)) ) \ .run(profile.r) # Search in the text in the name, title, position, summary. results = [] for profile in profiles: profile['match'] = self.calculate_score(text, profile) results.append(profile) return results
def execute_job(job_id): logging.info("Executing job with job_id: {0}".format(job_id)) job_dict = get_job(job_id) if not job_dict["is_active"]: logging.info("Job with job_id {0} is not active ! Execution stops !") return try: functionify(job_dict) if not job_dict["initialized"]: initialize_job(job_dict) while True: next_user = Profile.objects(job_id=job_id, authorized=True, finished=False).no_cache().order_by( "-crawling_score").first() try: process_user(job_dict, next_user) except RateLimitError: logging.warning("Rate Limit ! Adding job with job_id {} to waiting queue".format(job_id)) post_job_is_active(job_id, False) return # TODO : Add job id to waiting queue except Exception: logging.exception("An exception occurred ! Quitting job with id {}".format(job_id)) post_job_is_active(job_id, False)
def save_new_profiles(job_id, user_ids): pipeline = [ {"$group": { "_id": None, "distinct_ids": {"$push": "$id"} } }, { "$project": { "_id": 0, "new_ids": {"$setDifference": [user_ids, "$distinct_ids"]} } } ] response = Profile.objects(job_id=job_id).aggregate(*pipeline) new_user_ids = list(response)[0]["new_ids"] job_dict = get_job(job_id) functionify(job_dict) # Fetch profiles from Twitter and save to db twitter_profiles = get_profiles_from_twitter(job_dict["tweepy_api"], new_user_ids) profile_list = [create_profile_from_dict(job_dict, profile_dict) for profile_dict in twitter_profiles] Profile.objects.insert(profile_list)
def create_profile(): profile_fields = profile_schema.load(request.json) user_id = get_jwt_identity() user = User.query.get(user_id) if not user: return abort(401, description="Invalid user") new_profile = Profile() new_profile.name = profile_fields["name"] new_profile.restrictions = profile_fields["restrictions"] user.profiles.append(new_profile) db.session.commit() return jsonify(profile_schema.dump(new_profile))
def profile_create(user=None): user_id = get_jwt_identity() profile_fields = profile_schema.load(request.json) profile = Profile.query.get(user_id) if not profile: new_profile = Profile() new_profile.username = profile_fields["username"] new_profile.fname = profile_fields["fname"] new_profile.lname = profile_fields["lname"] new_profile.account_active = profile_fields["account_active"] new_profile.admin = profile_fields["admin"] user.profile.append(new_profile) db.session.add(new_profile) db.session.commit() return jsonify(profile_schema.dump(new_profile)) else: return abort(401, description='User Profile already exists')
def list_offers_loc(lat1, long1, update = False): key = 'list_offers_loc' + str(lat1) + str(long1) offers = memcache.get(key) if offers is None or update: logging.error('DB QUERY') #TODO impl logica para sacar las ofertas por localizacion offers = Profile.by_loc(lat1, long1) memcache.set(key, offers) return offers
def process_route(): pet_name = request.form['pet_name'] pet_breed = request.form['pet_breed'] pet_dob = request.form['pet_dob'] pet_sex = request.form['pet_sex'] diarydata = Profile(pet_name=pet_name, pet_breed=pet_breed, pet_dob=pet_dob, pet_sex=pet_sex) db.session.add(diarydata) db.session.commit() return redirect(url_for('index.index_load'))
def seed_db(): from models.User import User # Importing the User model from models.Profile import Profile # Importing the Profile model from main import bcrypt # Hashing module for the passwords from faker import Faker # Importing the faker module for fake data import random # Importing random from the python standard library faker = Faker() users = [] for i in range(5): # Do this 5 times user = User() # Create an user object from the User model user.email = f"test{i+1}@test.com" # Assign an email to the user object user.password = bcrypt.generate_password_hash("123456").decode("utf-8") # Assign ta hashed password to the user object db.session.add(user) # Add the user to the db session users.append(user) # Append the user to the users list db.session.commit() # Commit the seeion to the db for i in range(5): profile = Profile() # Create a profile object from the Profile model profile.username = faker.first_name() # Add a username to the profile object profile.firstname = faker.first_name() # Add a firstname to the profile object profile.lastname = faker.last_name() # Add a lastname to the profile object profile.user_id = users[i].id # Add a user_id to the profile object. This comes from real ids from the users list db.session.add(profile) # Add the profile to the session db.session.commit() # Commit the session to the database print("Tables seeded")
def profile_create(user): # This function will run when the route is matched if user.profile != []: # If the user already has a profile return abort(400, description="User already has profile" ) # Return the error "Email already in use" profile_fields = profile_schema.load( request.json) # Retrieving the fields from the request profile = Profile.query.filter_by( username=profile_fields["username"]).first( ) # Query the user table with the email and return the first user if profile: # If a user is returned return abort(400, description="username already in use" ) # Return the error "Email already in use" new_profile = Profile( ) # Create a new profile object from the Profile model new_profile.username = profile_fields[ "username"] # Add username to the new_profile new_profile.firstname = profile_fields[ "firstname"] # Add username to the new_profile new_profile.lastname = profile_fields[ "lastname"] # Add username to the new_profile new_profile.user_id = user.id # Add username to the new_profile user.profile.append(new_profile) # Add profile to the user db.session.commit() # Commit the DB session return jsonify( profile_schema.dump(new_profile)) # Return the newly created profile
def process_results(self, details): """ Processing the fields. :param details: The object we pulled from the DB. :return: The details object. """ # Check if the user exists. profile = Profile() cursor = profile.getTable().filter( r.row['user_id'] == details['user_id']).run(profile.r) results = list(cursor) if len(results) == 0: details = profile.insert(details) else: details['id'] = results[0]['id'] profile.update(details) return details
def get(self): lat1 = self.request.get("lat1") lon1 = self.request.get("lon1") #self.offers = list_offers_loc(lat1, lon1) #(53.4211041, -7.942588199999999) self.offers = offers = Profile.by_loc(lat1, lon1) logging.error('offers.results: %s' % type(self.offers.results)) logging.error('offers.results[0]: %s' % type(self.offers.results[0])) logging.error('offers.results[0].fields: %s' % type(self.offers.results[0].fields)) logging.error('al loro: %s' % self.offers) self.render('ioffer_offers_list.html', offers = self.offers)
def getProfilesFromData(self, path, browser): data = self.jsonHelper.readData(path) profiles = [] if data is not None: try: rootProfileData = data['profile'] infoCacheData = rootProfileData['info_cache'] for profileKey in infoCacheData: profileData = infoCacheData[profileKey] profileName = profileData['name'] profiles.append(Profile(browser, profileKey, profileName)) except: self.log.e(self.TAG, Error.ERROR_6012) return profiles
def create_profile_from_dict(job_dict, profile_dict): logging.info("create_profile_from_dict | profile_id: {0}".format(profile_dict["id"])) classifier_scores = {key: func(profile_dict) for key, func in job_dict["classifiers"].items()} crawling_score = job_dict["crawling_score"]({**profile_dict, **classifier_scores}) parameters = { "job_id": job_dict["id"], "profile": profile_dict, "user_id": profile_dict["id"], "classifier_scores": classifier_scores, "crawling_score": crawling_score, } return Profile(**parameters)
def get_profile_with_max_score(job_id): logging.info("get_profile_with_max_score | job_id: {0}".format(job_id)) try: profile = Profile.objects(job_id=job_id, authorized=True, finished=False).order_by("-crawling_score").first() except DoesNotExist: return None except Exception as e: logging.error("exception: {0}".format(str(e))) return {'error': str(e)} if profile is None: return {} return profile.to_dict()
def create_profile(): user = load_user(current_user.get_id()) if not user: return abort(401, description="Unauthorised to view this page") form = CreateProfile() if form.validate_on_submit(): new_profile = Profile( name=form.name.data, restrictions=form.restriction.data ) user.profiles.append(new_profile) db.session.commit() flash("Profile added!") return redirect(url_for("web_profiles.show_profiles")) return render_template("create_profile.html", form=form)
def seed_db(): from models.User import User # Importing the User model from models.Profile import Profile # Importing the Profile model from models.League import League from main import bcrypt # Hashing module for the passwords from faker import Faker # Importing the faker module for fake data import random # Importing random from the python standard library faker = Faker() users = [] leagues = [] for i in range(5): # Do this 5 times user = User() # Create an user object from the User model user.email = f"test{i+1}@test.com" # Assign an email to the user object user.password = bcrypt.generate_password_hash("123456").decode("utf-8") # Assign ta hashed password to the user object db.session.add(user) # Add the user to the db session users.append(user) # Append the user to the users list db.session.commit() # Commit the seeion to the db for i in range(5): profile = Profile() # Create a profile object from the Profile model profile.username = faker.first_name() # Add a username to the profile object profile.firstname = faker.first_name() # Add a firstname to the profile object profile.lastname = faker.last_name() # Add a lastname to the profile object profile.user_id = users[i].id # Add a user_id to the profile object. This comes from real ids from the users list db.session.add(profile) # Add the profile to the session db.session.commit() # Commit the session to the database for i in range(3): new_league = League() new_league.title = f"League title {i}" new_league.description = f"A nice league to the power of {i}" for i in range(3): new_league.users_leagues.append(users[i]) leagues.append(new_league) db.session.commit() for member in leagues[0].users_leagues: # print(f"League {i.title} => {i.account_id}") print(member.email) print("Tables seeded") # Print a message to let the user know they
def profile_create(user): if user.profile != []: return abort(400, description="User already has profile") profile_fields = profile_schema.load(request.json) profile = Profile.query.filter_by( username=profile_fields["username"]).first() if profile: return abort(400, description="username already in use") new_profile = Profile() new_profile.username = profile_fields["username"] new_profile.firstname = profile_fields["firstname"] new_profile.lastname = profile_fields["lastname"] new_profile.user_id = user.id user.profile.append(new_profile) db.session.commit() return jsonify(profile_schema.dump(new_profile))
#!/usr/bin/env python import os if __name__ == "__main__": from os import path from controllers.App import App from models.Profile import Profile from models.Course import Course from models.Topic import Topic from models.Book import Book app = App(path.dirname(path.realpath(__file__))) if path.exists('profile.md'): print('Publishing Profile') profile = Profile() app.publishProfile(profile) else: if path.exists('course.md'): print('Publishing full course') course = Course() app.publishCourse(course) else: if path.exists('topic.md'): print('Publishing topic + contained books') fullPath = os.getcwd() path, folder = os.path.split(fullPath) topic = Topic(folder) app.publishTopic(topic) else: print('Publishing single book')
def seed_db(): from models.User import User # Importing the User model from models.Profile import Profile # Importing the Profile model from models.Playlist import Playlist from models.Track import Track from models.Album import Album from models.Artist import Artist from models.AlbumType import AlbumType from models.Collection import Collection from main import bcrypt # Hashing module for the passwords from faker import Faker # Importing the faker module for fake data import random # Importing random from the python standard library faker = Faker() users = [] albums = [] album_types = ["SINGLE", "ALBUM", "COMPILATION"] for i in range(5): # Do this 5 times user = User() # Create an user object from the User model if i == 0: user.is_admin = True else: user.is_admin = False user.email = f"test{i+1}@test.com" # Assign an email to the user object user.password = bcrypt.generate_password_hash("123456").decode( "utf-8") # Assign ta hashed password to the user object db.session.add(user) # Add the user to the db session users.append(user) # Append the user to the users list db.session.commit() # Commit the seeion to the db for i in range(5): profile = Profile() # Create a profile object from the Profile model profile.username = faker.first_name( ) # Add a username to the profile object profile.firstname = faker.first_name( ) # Add a firstname to the profile object profile.lastname = faker.last_name( ) # Add a lastname to the profile object profile.user_id = users[ i].id # Add a user_id to the profile object. This comes from real ids from the users list db.session.add(profile) # Add the profile to the session db.session.commit() # Commit the session to the database for i in range(10): album = Album() album.name = faker.catch_phrase() db.session.add(album) albums.append(album) db.session.commit() for at in album_types: album_type = AlbumType() album_type.name = at album_type.album_id = random.choice(albums).album_id db.session.add(album_type) db.session.commit() for i in range(5): artist = Artist() artist.name = faker.name_nonbinary() db.session.add(artist) db.session.commit() for i in range(20): track = Track() track.name = faker.file_name() track.track_num = random.choice(range(20)) track.album_id = random.choice(albums).album_id track.disc_num = 1 track.duration_ms = 2500 track.explicit = True playlist = Playlist() # Create a playlist object from Playlist model playlist.name = faker.catch_phrase() playlist.owner_id = random.choice(users).id playlist.collaborative = False playlist.public = True collection = Collection( ) # Create a playlist object from Playlist model collection.name = faker.catch_phrase() collection.owner_id = random.choice(users).id collection.collaborative = False collection.public = True db.session.add(track) db.session.add(playlist) db.session.add(collection) db.session.commit() print("Tables seeded") # Print a message to let the user know they
def seed_db(): from models.Profile import Profile from models.User import User from models.Group import Group from models.Content import Content from models.Group_members import GroupMembers from models.Admin import Admin from main import bcrypt import random from faker import Faker faker = Faker() users = [] contents = [] profile_ids = list(range(1, 11)) random.shuffle(profile_ids) admins = [] for i in range(1, 6): user = User() user.email = f"test{i}@test.com" user.password = bcrypt.generate_password_hash("123456").decode("utf-8") user.subscription_status = random.choice([0, 1]) db.session.add(user) users.append(user) db.session.commit() print("User table seeded") for i in range(30): content = Content() content.title = faker.sentence() content.genre = faker.word() content.year = faker.year() db.session.add(content) contents.append(content) db.session.commit() print("Content table seeded") for i in range(10): content = random.sample(contents, k=2) restrictions = ("G", "PG", "M", "MA15+", "R18+") profile = Profile() profile.name = faker.first_name_nonbinary() profile.restrictions = random.choice(restrictions) profile.user_id = random.choice(users).user_id profile.unrecommend.extend(content) db.session.add(profile) db.session.commit() print("Profile table seeded") for i in range(10): content = random.sample(contents, k=3) group = Group() group.name = faker.word() group.description = faker.text() group.content.extend(content) admin = GroupMembers() admin.groups = group admin.profile_id = profile_ids.pop(0) admin.admin = True member_ids = [i for i in range(1, 11) if i != admin.profile_id] random.shuffle(member_ids) for i in range(2): member = GroupMembers() member.groups = group member.profile_id = member_ids.pop() member.admin = False db.session.add(group) db.session.commit() print("Group table seeded") for i in range(1, 3): admin = Admin() admin.username = f"Admin{i}" admin.password = bcrypt.generate_password_hash("654321").decode( "utf-8") db.session.add(admin) admins.append(admin) db.session.commit() print("Admin table seeded")
def test_skills_searching(): """ Testing the search by skills. """ profile = Profile() # First clean any data from the DB. if profile.tableExists(): profile.deleteTable() profile.createTable() # Create dummy entries. profile.insert(json.load(open('dummy_json/roy.json'))) profile.insert(json.load(open('dummy_json/david.json'))) profile.insert(json.load(open('dummy_json/nir.json'))) # Start to run tests against the API. First, get the application. client = TestClient(app) # Search by skills. json_response = client.post('/search-by-skills', json={'skill': 'Drupal'}) assert json_response.json()[0]['match'] == 11 # Search for JavaScript. json_response = client.post('/search-by-skills', json={'skill': 'JavaScript'}) matches = {'nirgn': 18, 'roy-segall-304b054a': 16, 'davidbronfen': 12} for profile in json_response.json(): assert profile["match"] == matches[profile['user_id']]
import rethinkdb as r from models.Profile import Profile from tools.SettingsManager import SettingsManager settings = SettingsManager().loadSettings() print("----------") print("Installing DB") r.db_create(settings['db']['name']).run( r.connect(settings['db']['host'], settings['db']['port'])) print("The DB " + settings['db']['name'] + " now exists.") print("----------") print("\n") print("----------") print("Installing Profile") profile = Profile() profile.createTable() print("The table now exists") print("----------")
def seed_db(): from models.User import User from models.Profile import Profile from faker import Faker from main import bcrypt from models.Equipment import Equipment from models.EquipmentOrder import EquipmentOrder import random from random import seed from random import randint faker = Faker() profiles = [] equipments = [] categories = ["dumbells", "cardio", "machine", "yoga", "mobility"] for i in range(10): user = User() user.email = f"test{i}@test.com" user.password = bcrypt.generate_password_hash("123456").decode("utf-8") db.session.add(user) db.session.commit() for i in range(10): profile = Profile() profile.username = faker.name() profile.fname = faker.first_name() profile.lname = faker.last_name() profile.account_active = faker.boolean() profile.user_id = i + 1 profiles.append(profile) db.session.add(profile) db.session.commit() for i in range(30): equipment = Equipment() equipment.equipment_name = faker.name() equipment.equipment_description = faker.catch_phrase() equipment.rented = random.choice([True, False]) equipment.rentpw = randint(8, 120) equipment.owner_id = random.choice(profiles).profileid equipment.category = random.choice(categories) equipments.append(equipment) db.session.add(equipment) for i in range(30): equipment_order = EquipmentOrder() equipment_order.order_begin_date = faker.date_between(start_date='-1y', end_date='today') equipment_order.order_return_date_estimate = faker.date_between( start_date='today', end_date='+1y') equipment_order.order_actual_return_date = faker.date_between( start_date='today', end_date='+1y') equipment_order.order_active = random.choice([True, False]) equipment_order.equipment_id = randint(1, 29) # equipment_order.equipment_id = random.choice(equipments).id equipment_order.hirer_id = random.choice(profiles).profileid db.session.add(equipment_order) db.session.commit() print("Tables seeded")
def seed_db(): from datetime import date from models.User import User # Importing the User model from models.Profile import Profile # Importing the Profile model from models.League import League from models.Member import Member from models.Fine import Fine from models.Point import Point from models.Category import Category from models.Sprint import Sprint from main import bcrypt # Hashing module for the passwords from faker import Faker # Importing the faker module for fake data import random # Importing random from the python standard library import copy import time faker = Faker() users = [] leagues = [] categories = [] sprints = [] points = [] fines = [] for i in range(5): time.sleep(0.2) user = User() user.email = f"test{i+1}@test.com" user.password = bcrypt.generate_password_hash("123456").decode("utf-8") db.session.add(user) users.append(user) db.session.commit() for i in range(5): # time.sleep(0.2) profile = Profile() profile.username = f"username{i}" profile.firstname = f"firstname{i}" profile.lastname = f"lastname{i}" profile.user_id = users[i].id db.session.add(profile) db.session.commit() for i in range(5): # time.sleep(0.2) new_league = League() new_league.title = f"League title {i}" new_league.description = f"A nice league to the power of {i}" new_league.owner = users[i].id leagues.append(new_league) db.session.add(new_league) db.session.commit() for i in range(5): # time.sleep(0.2) owner = Member() owner.user_id = leagues[i].owner owner.league_id = i + 1 owner.active = True db.session.add(owner) new_member = Member() new_member.active = True new_member.league_id = i + 1 new_member.user_id = random.choice(users).id while new_member.user_id == owner.user_id: new_member.user_id = random.choice(users).id db.session.add(new_member) db.session.commit() for i in range(5): new_sprint = Sprint() new_sprint.title = f"Sprint title #{i}" new_sprint.meeting_point = f"The Outback" new_sprint.creation_time = date.today() league = leagues[i] new_sprint.league = league sprints.append(new_sprint) db.session.commit() for i in range(5): # time.sleep(0.2) new_category = Category() new_category.title = f"category title {i}" new_category.description = f"category description {i}" if i % 2 == 0: private = True else: private = False new_category.private = private new_category.owner = random.choice(users).id new_category.leagues_categories.append(leagues[i]) categories.append(new_category) db.session.commit() for i in range(5): # time.sleep(0.2) new_fine = Fine() new_fine.title = f"Title {i}" new_fine.description = f"Description {i}" new_fine.amount = i if i % 2 == 0: style = "Award" else: style = "Fine" new_fine.style = style category = categories[i] new_fine.category = category fines.append(new_fine) db.session.commit() for i in range(4): # time.sleep(0.2) new_point = Point() new_point.creation_time = date.today() new_point.fine_id = random.choice(fines).id sprint = sprints[i] new_point.sprint = sprint new_point.giver_id = sprint.league.owner new_point.receiver_id = sprint.league.members[1].id db.session.commit() print("Tables seeded")