def get_basic_info(): """ Here we're asking the user for: - city - country - date - url - event_email And return all these information. """ click.echo( "Hello there! Let's create new Django Girls event! So exciting!") click.echo("Let's start with some basics.") city = click.prompt(click.style( "What is the name of the city?", bold=True, fg='yellow')) country = click.prompt(click.style( "What is the name of the country?", bold=True, fg='yellow')) date = gather_event_date_from_prompt() url = click.prompt(click.style( "What should be the URL of website? djangogirls.org/xxxx", bold=True, fg='yellow')) event_mail = click.prompt(click.style( "What is the mail adress of the event? [email protected]", bold=True, fg='yellow')) click.echo("Ok, got that! Your new event will happen in {0}, {1} on {2}".format( city, country, date)) return (city, country, date, url, event_mail)
def get_team(team): """ We're asking user for names and address of the rest of the team, and append that to a list we got from get_main_organizer """ add_team = click.confirm(click.style( "Do you want to add additional team members?", bold=True, fg='yellow'), default=False) i = 1 while add_team: i += 1 name = click.prompt(click.style( "First and last name of #{0} member".format(i), bold=True, fg='yellow')) email = click.prompt(click.style( "E-mail address of #{0} member".format(i), bold=True, fg='yellow')) if len(name) > 0: try: team.append({'first_name': name.split(' ')[ 0], 'last_name': name.split(' ')[1], 'email': email}) except IndexError: team.append( {'first_name': name, 'last_name': '', 'email': email}) click.echo("All right, the #{0} team member of Django Girls is {1} ({2})".format( i, name, email)) add_team = click.confirm(click.style( "Do you want to add additional team members?", bold=True, fg='yellow'), default=False) return team
def gather_information(): click.echo("Hello there sunshine! We're gonna copy an event website now.") event = get_event( click.prompt(click.style("First, give me the latest ID of the Event " "object you want to copy", bold=True, fg='yellow')) ) while not event: event = get_event(click.prompt("Wrong ID! Try again")) click.echo("Ok, we're copying {}, {}".format( event.city, event.country)) number = click.prompt(click.style("What is the number of the event in this city? " "If this is a second event, write 2. If third, then 3. You got it", bold=True, fg='yellow') ) date = gather_event_date_from_prompt() click.echo("The current team is: " + ", ".join( str(organizer) for organizer in event.team.all())) new_team = click.confirm(click.style( "Do you need to change the whole team?", bold=True, fg='yellow'), default=False ) return (event, number, date, new_team)
def gather_information(race_id, number): click.echo("Hello there! We are going to copy a race now.") # get race if not race_id: races = Race.objects.all().order_by("-start_datetime") for race in races: click.echo(f"{race.pk}. {race.title}") race = get_race( click.prompt( "First, give me the ID of the Race object we're gonna copy. If there is more than one race already, give me ID of the latest one." ) ) else: race = get_race(race_id) while not race: race = get_race(click.prompt("Wrong ID! Try again")) # get number if not number: number = click.prompt( "What is the number of the race? If this is a second race, write 2. If third, then 3. You got it" ) date = prepare_date( click.prompt("What is the date of this new race? (Format: MM/DD/YYYY)") ) while not date: date = prepare_date( click.prompt("Wrong format! Provide a date in format: MM/DD/YYYY)") ) return (race, number, date)
def get_basic_info(): """ Here we're asking the user for: - city - country - date - url - event_email And return all these information. """ click.echo( "Hello there! Let's create new Django Girls event! So exciting!") click.echo("Let's start with some basics.") city = click.prompt( click.style("What is the name of the city?", bold=True, fg='yellow')) country = click.prompt( click.style("What is the name of the country?", bold=True, fg='yellow')) date = gather_event_date_from_prompt() url = click.prompt( click.style("What should be the URL of website? djangogirls.org/xxxx", bold=True, fg='yellow')) event_mail = click.prompt( click.style( "What is the mail adress of the event? [email protected]", bold=True, fg='yellow')) click.echo( "Ok, got that! Your new event will happen in {0}, {1} on {2}".format( city, country, date)) return (city, country, date, url, event_mail)
def gather_information(): click.echo("Hello there sunshine! We're gonna copy an event website now.") event = get_event( click.prompt( click.style( "First, give me the latest ID of the Event " "object you want to copy", bold=True, fg='yellow'))) while not event: event = get_event(click.prompt("Wrong ID! Try again")) click.echo("Ok, we're copying {}, {}".format(event.city, event.country)) number = click.prompt( click.style( "What is the number of the event in this city? " "If this is a second event, write 2. If third, then 3. You got it", bold=True, fg='yellow')) date = gather_event_date_from_prompt() click.echo("The current team is: " + ", ".join(str(organizer) for organizer in event.team.all())) new_team = click.confirm(click.style( "Do you need to change the whole team?", bold=True, fg='yellow'), default=False) return (event, number, date, new_team)
def get_team(team): """ We're asking user for names and address of the rest of the team, and append that to a list we got from get_main_organizer """ add_team = click.confirm(click.style( "Do you want to add additional team members?", bold=True, fg='yellow'), default=False) i = 1 while add_team: i += 1 name = click.prompt( click.style("First and last name of #{0} member".format(i), bold=True, fg='yellow')) email = click.prompt( click.style("E-mail address of #{0} member".format(i), bold=True, fg='yellow')) if len(name) > 0: team.append({'name': name, 'email': email}) click.echo( "All right, the #{0} team member of Django Girls is {1} ({2})". format(i, name, email)) add_team = click.confirm(click.style( "Do you want to add additional team members?", bold=True, fg='yellow'), default=False) return team
def get_organizer_data(): """ Returns a dictionary with first_name, last_name and email """ main_name = click.prompt( click.style("First and last name", bold=True, fg='yellow')) main_email = click.prompt( click.style("E-mail address", bold=True, fg='yellow')) data = {'name': main_name, 'email': main_email} return data
def command(ctx, username, create, batch): """ Update or optionally create password, name and type of a user. USERNAME : The username of the user to process. """ User = rt.models.users.User UserTypes = rt.models.users.UserTypes try: user = User.objects.get(username=username) if create: raise click.UsageError( "Cannot create existing user named '{}'".format(username)) except User.DoesNotExist: if create: user = User(username=username) click.echo("Creating new user") else: raise click.UsageError( "We have no user named '{}'".format(username)) dut = user.user_type or UserTypes.user if not batch: user.first_name = click.prompt("First name", default=user.first_name or username) user.last_name = click.prompt("Last name", default=user.last_name or username) user_type = click.prompt("User type", type=click.Choice([ ut.name for ut in UserTypes.get_list_items() if ut.name ]), default=dut.name) if user_type: user.user_type = UserTypes.get_by_name(user_type) else: user.user_type = None passwd = click.prompt( "Password (leave blank to deactivate user account)", hide_input=True, confirmation_prompt=True, default='') if passwd: user.set_password(passwd) else: user.set_unusable_password() user.full_clean() if batch or yes_or_no('Going to save {}. Are you sure?'.format(user)): user.save() click.echo("User {} has been saved.".format(user))
def get_main_organizer(): """ We're asking user for name and address of main organizer, and return a list of dictionary. """ team = [] click.echo("Now let's talk about the team. First the main organizer:") main_name = click.prompt(click.style("First and last name", bold=True, fg="yellow")) main_email = click.prompt(click.style("E-mail address", bold=True, fg="yellow")) team.append({"name": main_name, "email": main_email}) click.echo("All right, the main organizer is {0} ({1})".format(main_name, main_email)) return team
def get_organizer_data(): """ Returns a dictionary with first_name, last_name and email """ main_name = click.prompt(click.style( "First and last name", bold=True, fg='yellow')) main_email = click.prompt(click.style( "E-mail address", bold=True, fg='yellow')) data = { 'name': main_name, 'email': main_email } return data
def command(): """Generate "Next events" section for the Dispatch.""" now = timezone.now() raw_dispatch_date = click.prompt(click.style( "What is the date of the previous Dispatch? (Format: YYYY-MM-DD)", bold=True, fg='yellow')) dispatch_date = (datetime.datetime .strptime(raw_dispatch_date, "%Y-%m-%d") .replace(tzinfo=datetime.timezone.utc)) # Get the events that happened since the last Dispatch. click.echo(click.style("PREVIOUS EVENTS", bold=True)) previous_events = Event.objects.filter( date__gt=dispatch_date.strftime("%Y-%m-%d"), date__lt=now.strftime("%Y-%m-%d")) result_previous = generate_html_content(previous_events) num_events = len(result_previous) if result_previous: click.echo( "%s event%s happened since the last dispatch: " % (apnumber(num_events), "s" if num_events > 1 else "") + ", ".join(result_previous) + ".") else: click.echo("No event took place since the last Dispatch.") # Get the events that were created since the last Dispatch. click.echo(click.style("NEXT EVENTS", bold=True)) next_events = Event.objects.all().filter( created_at__range=(dispatch_date, now)).order_by("date") sorted_event = groupby(next_events, key=lambda event: event.date.month) if next_events: for month, events in sorted_event: month_list = generate_html_content(events) click.echo(calendar.month_name[ month] + ": " + ", ".join(month_list) + "." + "<br />") else: click.echo( "There's no new event to announce. Don't forget to check our " "<a href='https://djangogirls.org/events/'>website</a> to get a " "list of our events planned for the next few months.") # Get the events with open registration. click.echo("OPEN REGISTRATION") open_events = Event.objects.all().filter( form__open_from__lte=now, form__open_until__gte=now) result_open = generate_html_content(open_events) if result_open: click.echo("Registrations are still open for: " + ", ".join(result_open) + ".") else: click.echo("There's no event with open registration.")
def command(): """Creates new Django Girls organizer""" event_id = click.prompt(click.style( "What's the event ID? NOT the event page ID. We want EVENT ID here", bold=True, fg='yellow')) event = Event.objects.get(id=event_id) click.echo("Ok, we're adding to an event in {}, {}".format( event.city, event.country)) team = [get_organizer_data()] while click.confirm( click.style("Do you want to add additional team members?", bold=True, fg='yellow'), default=False): team.append(get_organizer_data()) click.echo("OK! That's it. Now I'll add your organizers.") members = create_users(team, event) for member in members: click.echo( "User {} has been added and notified".format(member.email)) click.echo(DELIMITER) click.echo("You still need to invite people to Google Group!")
def command(): """Creates new Django Girls organizer""" event_id = click.prompt( click.style( "What's the event ID? NOT the event page ID. We want EVENT ID here", bold=True, fg='yellow')) event = Event.objects.get(id=event_id) click.echo("Ok, we're adding to an event in {}, {}".format( event.city, event.country)) team = [get_organizer_data()] while click.confirm( click.style("Do you want to add additional team members?", bold=True, fg='yellow'), default=False): team.append(get_organizer_data()) click.echo("OK! That's it. Now I'll add your organizers.") members = create_users(team, event) for member in members: click.echo("User {} has been added and notified".format(member.email)) click.echo(DELIMITER) click.echo("You still need to invite people to Google Group!")
def get_organizer_data(): """ Returns a dictionary with first_name, last_name and email """ main_name = click.prompt(click.style( "First and last name", bold=True, fg='yellow')) main_email = click.prompt(click.style( "E-mail address", bold=True, fg='yellow')) try: data = {'first_name': main_name.split(' ')[0], 'last_name': main_name.split(' ')[1], 'email': main_email} except IndexError: data = {'first_name': main_name, 'last_name': '', 'email': main_email} return data
def get_main_organizer(): """ We're asking user for name and address of main organizer, and return a list of dictionary. """ team = [] click.echo("Now let's talk about the team. First the main organizer:") main_name = click.prompt( click.style("First and last name", bold=True, fg='yellow')) main_email = click.prompt( click.style("E-mail address", bold=True, fg='yellow')) team.append({'name': main_name, 'email': main_email}) click.echo(u"All right, the main organizer is {0} ({1})".format( main_name, main_email)) return team
def login(): click.echo('Please login.') username = click.prompt('Username', type=str) password = click.prompt('Password', type=str) # authenticate user using requests - CHANGE URL TO HEROKU AFTER DEVELOPMENT r = requests.post( 'http://afternoon-fortress-38321.herokuapp.com/fda_login/', data={ 'username': username, 'password': password }) if (r.status_code == requests.codes.ok): if click.confirm('Would you like to encrypt a file?'): encrypt_file() view_files(username) else: click.echo('Invalid username and password') login()
def gather_information(): click.echo("Hello there sunshine! We're gonna copy an event website now.") event = get_event( click.prompt( "First, give me the ID of the Event object we're gonna copy. " "Don't mix it up with EventPage object. If there is more than " "one event in this city already, give me ID of the latest one")) while not event: event = get_event(click.prompt("Wrong ID! Try again")) number = click.prompt( "What is the number of the event in this city? " "If this is a second event, write 2. If third, then 3. You got it") date = gather_event_date_from_prompt() return (event, number, date)
def create_staff_user(): click.echo("--- Creating a staff user ---") email = click.prompt("Please enter email address for staff user") if "@" not in email: click.abort("'{email}' does not appear to be a valid email address") password = click.prompt("Please enter password for this user", hide_input=True) password2 = click.prompt("Please confirm password for this user", hide_input=True) if password != password2: click.abort("Passwords don't match") user = User.objects.create(email=email, is_staff=True, is_superuser=False) user.set_password(password) user.save() click.echo(f"-- Staff User {email} created ---")
def gather_event_date_from_prompt(): date = None while date is None: date_str = click.prompt( click.style("What is the date of the event? (Format: DD/MM/YYYY or MM/YYYY)", bold=True, fg="yellow") ) date = get_approximate_date(date_str) if date is None: click.secho("Wrong format! Try again :)", bold=True, fg="red") return date
def get_main_organizer(): """ We're asking user for name and address of main organizer, and return a list of dictionary. """ team = [] click.echo("Now let's talk about the team. First the main organizer:") main_name = click.prompt(click.style( "First and last name", bold=True, fg='yellow')) main_email = click.prompt(click.style( "E-mail address", bold=True, fg='yellow')) try: team.append({'first_name': main_name.split(' ')[ 0], 'last_name': main_name.split(' ')[1], 'email': main_email}) except IndexError: team.append({'first_name': main_name, 'last_name': '', 'email': main_email}) click.echo(u"All right, the main organizer is {0} ({1})".format( main_name, main_email)) return team
def gather_information(): click.echo("Hello there sunshine! We're gonna copy an event website now.") event = get_event( click.prompt( "First, give me the ID of the Event object we're gonna copy. " "Don't mix it up with EventPage object. If there is more than " "one event in this city already, give me ID of the latest one" ) ) while not event: event = get_event(click.prompt("Wrong ID! Try again")) number = click.prompt( "What is the number of the event in this city? " "If this is a second event, write 2. If third, then 3. You got it" ) date = gather_event_date_from_prompt() return (event, number, date)
def gather_event_date_from_prompt(): date = None while date is None: date_str = click.prompt( click.style( "What is the date of the event? (Format: DD/MM/YYYY or MM/YYYY)", bold=True, fg='yellow')) date = get_approximate_date(date_str) if date is None: click.secho("Wrong format! Try again :)", bold=True, fg='red') return date
def view_report_contents(reports_list): report_name = click.prompt('Which report would you like to display?') # get report ID check = False report_id = 0 for r in reports_list: if r['report_title'] == report_name: report_id = r['report_id'] check = True if check is False: click.echo( 'No existing report with that name. Please enter another report.') view_report_contents(reports_list) else: # get report contents - CHANGE URL TO HEROKU AFTER DEVELOPMENT r = requests.post( 'http://afternoon-fortress-38321.herokuapp.com/fda_view_report_contents/', {'report_id': report_id}) if r.status_code == 200: json_str = r.text r_info = json.loads(json_str) report_info = r_info['report_info'] # display report contents click.echo('Title: ' + report_info['title']) click.echo('Owner: ' + report_info['owner']) click.echo('Short Description: ' + report_info['short_desc']) click.echo('Summary: ' + report_info['long_desc']) click.echo('Shared With: ' + report_info['shared_with']) click.echo('Created: ' + report_info['timestamp']) click.echo('Files: ') for r in report_info['files']: click.echo(r) if report_info['files'] == []: if click.confirm( "Would you like to view another report's contents?"): view_report_contents(reports_list) else: click.echo('Goodbye then.') exit() else: check_download(report_info['files'], report_id, reports_list, report_info['files_encrypted']) elif r.status_code == 404: click.echo('You do not currently have any reports. Goodbye.') else: click.echo('Error. Please contact site manager.') exit()
def encrypt_file(): key = random_generator(256) file_name = click.prompt('Enter the path of the file you wish to encrypt') try: encrypt(file_name, key) except FileNotFoundError: click.echo('ERROR: File not found') encrypt_file() pk_file_name = file_name + '.pem' with open(pk_file_name, 'wb') as f: f.write(b64encode(key)) click.echo('Encrypted file saved as {}.enc'.format(file_name)) click.echo('Keyfile saved as {}'.format(pk_file_name)) if click.confirm('Would you like to encrypt another file?'): encrypt_file() exit()
def check_download(files, report_id, reports_list, files_encrypted): if click.confirm("Would you like to download a file from this report?"): file = click.prompt('Please enter the name of the file') check = False for f in files: if f == file: check = True if check is False: click.echo('No existing file with that name.') check_download(files, report_id, reports_list, files_encrypted) else: download_files(report_id, reports_list, file, files_encrypted) else: if click.confirm("Would you like to view another report's contents?"): view_report_contents(reports_list) else: click.echo('Goodbye then.') exit()
def command(): """Creates new Django Girls organizer""" event_id = click.prompt( click.style( "What's the event ID? NOT the event page ID. We want EVENT ID here", bold=True, fg='yellow')) event = Event.objects.get(id=event_id) click.echo("Ok, we're adding to an event in {}, {}".format( event.city, event.country)) team = [get_organizer_data()] while click.confirm( click.style("Do you want to add additional team members?", bold=True, fg='yellow'), default=False): team.append(get_organizer_data()) click.echo("OK! That's it. Now I'll add your organizers.") members, members_as_list = create_users(team) for member in members: event.team.add(member) event.save() for member in members_as_list: if 'password' in member: click.echo("{} - email: {} password {}".format( member['first_name'], member['email'], member['password'])) else: click.echo( "{} - email: {} already has account".format( member['first_name'], member['email'])) click.echo(DELIMITER) invite_team_to_slack(members) click.echo(DELIMITER) click.echo("You still need to invite people to Google Group!")
def download_files(report_id, reports_list, file_name, files_encrypted): # get report files - CHANGE URL TO HEROKU AFTER DEVELOPMENT r = requests.post( 'http://afternoon-fortress-38321.herokuapp.com/fda_get_files/', { 'report_id': report_id, 'file_name': file_name }) if files_encrypted: if click.confirm("Do you have the private key?"): key_file = click.prompt( 'Enter the path to the keyfile for this file') key = None try: with open(key_file, 'rb') as f: key = b64decode(f.read()) out_name = file_name if file_name.split('.')[-1] == 'enc': out_name = file_name[:-4] decrypt_file(file_name, key, out_name) except FileNotFoundError: click.echo('ERROR: Keyfile not found') exit() click.echo('File saved as {}'.format(out_name)) else: click.echo('You cannot download the file.') if click.confirm( "Would you like to view another report's contents?"): view_report_contents(reports_list) else: click.echo('Goodbye then.') exit() else: file = open(file_name, 'wb') file.write(r.content) file.close() click.echo('Success. Your file has been downloaded.') if click.confirm("Would you like to view another report's contents?"): view_report_contents(reports_list) else: click.echo('Goodbye then.') exit()
def command(): """Creates new Django Girls organizer""" event_id = click.prompt(click.style( "What's the event ID? NOT the event page ID. We want EVENT ID here", bold=True, fg='yellow')) event = Event.objects.get(id=event_id) click.echo("Ok, we're adding to an event in {}, {}".format( event.city, event.country)) team = [get_organizer_data()] while click.confirm( click.style("Do you want to add additional team members?", bold=True, fg='yellow'), default=False): team.append(get_organizer_data()) click.echo("OK! That's it. Now I'll add your organizers.") members, members_as_list = create_users(team) for member in members: event.team.add(member) event.save() for member in members_as_list: if 'password' in member: click.echo("{} - email: {} password {}".format( member['first_name'], member['email'], member['password'])) else: click.echo( "{} - email: {} already has account".format( member['first_name'], member['email'])) click.echo(DELIMITER) invite_team_to_slack(members) click.echo(DELIMITER) click.echo("You still need to invite people to Google Group!")
def command(database, db_override, host_override, pg_home, filename, no_confirm): """ Django management command to restore a PostgreSQL database. """ db = db_override or settings.DATABASES[database]["NAME"] host = host_override or settings.DATABASES[database]["HOST"] psql = os.path.join(pg_home, "bin", "psql") if pg_home else "psql" pg_restore = os.path.join(pg_home, "bin", "pg_restore") if pg_home else "pg_restore" if filename is None: backup_path = get_backup_path() backup_files = [ f for f in os.listdir(backup_path) if os.path.isfile(os.path.join(backup_path, f)) ] num_backup_files = len(backup_files) if num_backup_files: click.secho("There are {num} backup files in '{backup_path}'. " "Which would you like to restore?".format( num=num_backup_files, backup_path=backup_path, )) for key, value in enumerate(backup_files, 1): click.secho("{option_number}: {file}".format( option_number=key, file=value, )) file_choice = click.prompt("Enter number of the file to restore", type=int) filename = "{path}/{file}".format( path=backup_path, file=backup_files[file_choice - 1], ) else: raise ValueError( 'No input file was provided by the "--file" parameter, and there are ' "no files in {backup_path}.".format(backup_path=backup_path, )) if not os.path.isfile(filename): raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), filename) if no_confirm: confirm = "yes" else: click.secho( "About to restore '{db}' on host '{host}' from the file:\n" "'{file}'\n" "THIS WILL OVERWRITE THE DATABASE.".format( db=db, host=host, file=filename, ), fg="red", bold=True, ) confirm = click.prompt('Type "yes" to start the restore', default="no") if confirm == "yes": os.environ["PGPASSWORD"] = settings.DATABASES[database]["PASSWORD"] os.system( '{psql} -h {host} -U {user} -d {db} -c "DROP OWNED BY {user};"'. format( psql=psql, host=host, user=settings.DATABASES[database]["USER"], db=db, )) os.system( "{pg_restore} -c --if-exists -h {host} -U {user} -d {db} {file}". format( pg_restore=pg_restore, host=host, user=settings.DATABASES[database]["USER"], db=db, file=filename, )) os.environ["PGPASSWORD"] = "" else: click.secho( 'Bailing out; you did not type "yes".', fg="green", )
def command(database, filename): """ Django management command to restore a PostgreSQL database. """ if filename is None: backup_path = get_backup_path() backup_files = [ f for f in os.listdir(backup_path) if os.path.isfile(os.path.join(backup_path, f)) ] num_backup_files = len(backup_files) if num_backup_files: click.secho( "There are {num} backup files in '{backup_path}'. Which would you like to restore?" .format( num=num_backup_files, backup_path=backup_path, )) for key, value in enumerate(backup_files, 1): click.secho('{option_number}: {file}'.format( option_number=key, file=value, )) file_choice = click.prompt( 'Enter the number of the file to restore', type=int) filename = '{path}/{file}'.format( path=backup_path, file=backup_files[file_choice - 1], ) else: raise ValueError( 'No input file was provided by the "--file" parameter, and there are no files in {backup_path}.' .format(backup_path=backup_path, )) if not os.path.isfile(filename): raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), filename) click.secho( "About to restore '{db}' on host '{host}' from the file '{filename}'. THIS WILL OVERWRITE THE DATABASE." .format( db=settings.DATABASES[database]['NAME'], host=settings.DATABASES[database]['HOST'], filename=filename, ), fg="red", bold=True, ) confirm = click.prompt('Type "yes" to start the restore', default='no') if confirm == "yes": os.environ["PGPASSWORD"] = settings.DATABASES[database]['PASSWORD'] os.system( 'psql -h {host} -U {username} -d {db} -c "DROP OWNED BY {username};"' .format( host=settings.DATABASES[database]['HOST'], username=settings.DATABASES[database]['USER'], db=settings.DATABASES[database]['NAME'], )) os.system( 'pg_restore -c --if-exists -h {host} -U {username} -d {db} {file}'. format( host=settings.DATABASES[database]['HOST'], username=settings.DATABASES[database]['USER'], db=settings.DATABASES[database]['NAME'], file=filename, )) os.environ["PGPASSWORD"] = '' else: click.secho( 'Bailing out; you did not type "yes".', fg="green", )