Best Python code snippet using autotest_python
backup_restore.py
Source:backup_restore.py  
1#!/usr/bin/env python2# Copyright (c) 2013 Riverbed Technology, Inc.3#4# This software is licensed under the terms and conditions of the 5# MIT License set forth at:6#   https://github.com/riverbed/flyscript/blob/master/LICENSE ("License").  7# This software is distributed "AS IS" as set forth in the License.8"""9This script performs backup and restores of configuration10to a Shark appliance.11"""12import sys13import json14import getpass15from rvbd.common.utils import DictObject16from rvbd.shark.app import SharkApp17class BackupApp(SharkApp):18    config_types = ['basic', 'auth', 'jobs', 'profiler_export', 'audit', 'protocols', 'users']19    def add_options(self, parser):20        parser.add_option('-f', '--filename',21                          help='Filename to use for backup/restore')22        parser.add_option('-b', '--backup', action='store_true',23                          help='Backup mode: store configuration to the specified file')24        parser.add_option('-r', '--restore', action='store_true',25                          help='Restore mode: apply configuration from the specified file')26        parser.add_option('-t', '--types',27                          help='Optional comma-separate list to limit the configuration '28                               'type(s) to backup/restore (options are %s).' %29                               (', '.join(self.config_types)))30    def main(self):31        if self.options.types is None:32            self.types = self.config_types33        else:34            self.types = self.options.types.split(',')35            for t in self.types:36                if not t in self.config_types:37                    raise ValueError("Invalid configuration type %s" % t)38        if self.options.filename is None:39            raise ValueError("Must specify backup/restore file")40        if self.options.backup:41            self.backup()42        elif self.options.restore:43            self.restore()44        else:45            raise RuntimeError("either backup mode (-b) or restore mode (-r) "46                               "must be specified")47    def backup(self):48        # First see if the file is there and if it has anything in it49        # already, parse it50        self.config = {}51        try:52            f = open(self.options.filename)53            self.config = json.load(f, object_hook=DictObject.create_from_dict)54            f.close()55        except Exception, e:56            print e, e.__class__57        print "Starting backup..."58        f = open(self.options.filename, 'w')59        for t in self.types:60            if t == 'basic':61                print "Backing up basic configuration..."62                self.config['basic'] = self.shark.api.settings.get_basic()63            elif t == 'auth':64                print "Backing up authentication settings..."65                self.config['auth'] = self.shark.api.settings.get_auth()66            elif t == 'audit':67                print "Backing up audit settings..."68                self.config['audit'] = self.shark.api.settings.get_audit()69            elif t == 'profiler_export':70                print "Backing up profiler export settings..."71                self.config['profiler_export'] = self.shark.api.settings.get_profiler_export()72            elif t == 'protocols':73                print "Backing up protocol names / protocol groups..."74                self.config['protocol_groups'] = self.shark.api.settings.get_protocol_groups()75                self.config['protocol_names'] = self.shark.api.settings.get_protocol_names()76            elif t == 'jobs':77                print "Backing up jobs..."78                self.config['jobs'] = [j.config for j in self.shark.api.jobs.get_all()]79            elif t == 'users':80                print "Backing up users and groups..."81                self.config['users'] = self.shark.api.auth.users.get_all()82                self.config['groups'] = self.shark.api.auth.groups.get_all()83        json.dump(self.config, f, indent=4)84        print "Backup complete."85    def restore(self):86        print 'This operation will overwrite any existing configuration on your '87        print 'Shark appliance.  Please verify that you want to continue.'88        result = raw_input('Continue?  [y/N] > ')89        if result not in ('Y', 'y'):90            print 'Okay, exiting.'91            sys.exit()92        f = open(self.options.filename)93        self.config = json.load(f, object_hook=DictObject.create_from_dict)94        f.close()95        print "Starting restore..."96        for t in self.types:97            if t == 'basic':98                print "Restoring basic configuration..."99                # XXX/demmer we may not want to do this since this100                # could change the IP address101                self.shark.api.settings.update_basic(self.config['basic'])102            elif t == 'auth':103                print "Restoring authentication settings..."104                self.shark.api.settings.update_auth(self.config['auth'])105                print "Restoring (reconnecting to shark...)"106                self.connect()107            elif t == 'audit':108                print "Restoring audit settings..."109                self.shark.api.settings.update_audit(self.config['audit'])110            elif t == 'profiler_export':111                print "Restoring profiler export settings..."112                self.shark.api.settings.update_profiler_export(self.config['profiler_export'])113            elif t == 'protocols':114                print "Restoring protocol names / protocol groups..."115                self.shark.api.settings.update_protocol_names(self.config['protocol_names'])116                self.shark.api.settings.update_protocol_groups(self.config['protocol_groups'])117            elif t == 'jobs':118                print "Restoring jobs..."119                # Don't blow away existing jobs with the same configuration120                job_config = self.shark.api.jobs.get_all()121                config_by_name = {}122                for j in job_config:123                    config_by_name[j.config.name] = j.config124                for new_job in self.config['jobs']:125                    if new_job.name in config_by_name:126                        if new_job == config_by_name[new_job.name]:127                            print "%s (skipped since already configured)..." % new_job.name128                        else:129                            print ("%s (ERROR: job exists with different configuration)..."130                                   % new_job.name)131                        continue132                    print "%s (configured)..." % new_job.name133                    self.shark.api.jobs.add(new_job)134            elif t == 'users':135                print "Restoring groups..."136                # Don't blow away existing groups with the same configuration137                group_config = self.shark.api.auth.groups.get_all()138                config_by_name = {}139                for g in group_config:140                    config_by_name[g.name] = g141                for new_group in self.config['groups']:142                    if new_group.name in config_by_name:143                        if new_group == config_by_name[new_group.name]:144                            print "%s (skipped since already configured)..." % new_group.name145                        else:146                            print ("%s (ERROR: group exists with different configuration)..."147                                   % new_group.name)148                        continue149                    print "%s..." % new_group.name150                    self.shark.api.auth.groups.add(new_group)151                print "Restoring users..."152                user_config = self.shark.api.auth.users.get_all()153                config_by_name = {}154                for u in user_config:155                    config_by_name[u.name] = u156                for new_user in self.config['users']:157                    if new_user.name in config_by_name:158                        if new_user == config_by_name[new_user.name]:159                            print "%s (skipped since already configured)..." % new_user.name160                        else:161                            print ("%s (ERROR: user exists with different configuration)..."162                                   % new_user.name)163                        continue164                    print "%s..." % new_user.name165                    # Need to coerce the structure for a new user166                    del new_user['is_admin']167                    del new_user['is_locked']168                    while True:169                        passwd = getpass.getpass("Enter password: ")170                        passwd2 = getpass.getpass("Enter password (again): ")171                        if passwd != passwd2:172                            print "ERROR: passwords do not match"173                            continue174                        new_user['password'] = passwd175                        break176                    self.shark.api.auth.users.add(new_user)177        print "Restore complete."178if __name__ == '__main__':...application.py
Source:application.py  
1import logging2from flask import Flask, Blueprint3from flask_sqlalchemy import SQLAlchemy4from flask_restplus import Api5from flask_jwt_extended import JWTManager6from .config import config_by_name7logging.basicConfig(level=logging.DEBUG, format='[%(asctime)s] %(levelname)s: %(message)s')8db = SQLAlchemy()9app = Flask(__name__, instance_relative_config=True)10app.config.from_object(config_by_name['dev'])11db.init_app(app)12jwt = JWTManager(app)13def create_app(config_name='dev'):14    global app15    app.config.from_object(config_by_name[config_name])16    bp = Blueprint('api', __name__, url_prefix='/api')17    api = Api(bp,18        title='WebApp',19        description='Add description here',20        version='0.0.1',21        security='Bearer Auth',22        authorizations={23            'Bearer Auth': {24                'type': 'apiKey',25                'in': 'header',26                'name': 'Authorization'27            },28        },29        ordered=True,30        terms_url='https://andrei.cioara.me',31        license='MIT',32        license_url='https://andrei.cioara.me',33    )34    from .views.dinosaur_views import api as dinosaur_ns35    api.add_namespace(dinosaur_ns)36    app.register_blueprint(bp)...config.py
Source:config.py  
1import os2base_dir = os.path.abspath(os.path.dirname(__file__))3class Config:4    SECRET_KEY = os.getenv("SECRET_KEY", os.urandom(24))5    DEBUG = False6class ProductConfig(Config):    7    MONGO_URI = "localhost:27017/"8    MONGO_DBNAME = "product_db"9class DevelopmentConfig(Config):10    DEBUG = True11    SECRET_KEY = "dev_secret_key"12    MONGO_URI = "localhost:27017/"13    MONGO_DBNAME = "dev_db"14class TestConfig(Config):15    DEBUG = True16    SECRET_KEY = "test_secret_key"17    MONGO_URI = "localhost:27017/"18    MONGO_DBNAME = "test_db"19config_by_name = dict(20    prod=ProductConfig,21    dev=DevelopmentConfig,22    test=TestConfig23)24def from_object(config_name=None):25    if config_name is not None:26        return config_by_name[config_name]27    env_config_name = os.getenv("FLASK_ENV", None)28    if env_config_name is not None:29        return config_by_name[env_config_name]30        31    default_config_name = 'dev'...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
