Пример #1
0
    def __init__(self):
        endpoint = "https://synapsel1nk1.documents.azure.com:443/"
        key = "zM8dZNCWIi03JWziWAr2JGBlU2uEsmU1651YA4p5HCKp1DpGeQ0fH3gNDCHVEId5JIhHXhTI7Rkfnl4pZurqfg=="
        # create_cosmos_client
        client = CosmosClient(endpoint, key)

        database_name = 'lvtn_database'
        client.create_database_if_not_exists(database_name)
        database = client.get_database_client(database_name)
        container_name = 'parsed_data'
        self.container = database.get_container_client(container_name)
Пример #2
0
    def __init__(self):
        endpoint = "https://synapsel1nk.documents.azure.com:443/"
        key = "r0EEApAfBwKARscLmgjPzdAYVVxFbLy5pOf2AU0yLL6FrcHFjySI3NYnb5zpHSvVPFkvRKI4yUTTRIZTmt4mCg=="
        # create_cosmos_client
        client = CosmosClient(endpoint, key)

        database_name = 'lvtn_database'
        client.create_database_if_not_exists(database_name)
        database = client.get_database_client(database_name)
        container_name = 'parsed_data'
        self.container = database.get_container_client(container_name)
Пример #3
0
def main(req: func.HttpRequest) -> func.HttpResponse:

    # Initialize the Cosmos client
    endpoint = "https://parking-spots.documents.azure.com:443/"
    key = 'c9av0FP6xBrnz7XNUdBNIUFdCuo1IvE3H2SWvvB8Pxo92ALKzfW2gDXxgQlBlyUJtLDiJSZK6Ew8YO8yPNepnA=='
    client = CosmosClient(endpoint, key)

    # Select database
    database_name = 'Parking-Data'
    database = client.create_database_if_not_exists(id=database_name)

    # Select container
    container_name = 'Items'
    container = database.create_container_if_not_exists(
        id=container_name,
        partition_key=PartitionKey(path="/slots"),
        offer_throughput=400
    )

    # Query slots using SQL
    query = "SELECT * FROM c"

    items = list(container.query_items(
        query=query,
        enable_cross_partition_query=True
    ))

    return func.HttpResponse(json.dumps(items))
Пример #4
0
def get_item(request, pk, name):
    context = {'item': [], 'status_text': 'ok', 'created': {}}
    client = CosmosClient(endpoint, key)
    database = client.create_database_if_not_exists(id=database_name)
    container = database.create_container_if_not_exists(
        id=container_name,
        partition_key=PartitionKey(path="/name"),
        offer_throughput=400)
    print(request)
    if request.method == "DELETE":
        print('delete')
        try:
            container.delete_item(item=pk, partition_key=name)
        except CosmosResourceNotFoundError:
            return HttpResponse("Resource not Found")
        return redirect('http://127.0.0.1:8000')
        # return render(request, template_name='index.html', context=context)
    elif request.method == 'POST':
        item = {
            'id': request.POST.get('id'),
            'name': request.POST.get('name'),
            'age': request.POST.get('age'),
            'category': request.POST.get('category'),
            'picture': request.POST.get('picture')
        }
        # picture = request.FILES.get('picture')
        # item = push_image(picture, request.POST['name'], request.POST['age'], request.POST['category'])
        container.replace_item(item=item['id'], body=item)
        context['item'] = [item]
        return render(request, template_name='index.html', context=context)
    else:
        item = container.read_item(pk, partition_key=name)
        context['item'] = item
    return render(request, template_name='index.html', context=context)
Пример #5
0
def hello(request):
    context = {'items': [], 'status_text': 'ok', 'created': {}}
    client = CosmosClient(endpoint, key)
    database = client.create_database_if_not_exists(id=database_name)
    container = database.create_container_if_not_exists(
        id=container_name,
        partition_key=PartitionKey(path="/name"),
        offer_throughput=400)
    query = "SELECT * FROM c items"
    items = list(
        container.query_items(query=query, enable_cross_partition_query=True))
    context['items'] = items
    if request.method == 'GET':
        return render(request, template_name='index.html', context=context)
    elif request.method == 'POST':
        picture = request.FILES.get('picture')
        item = push_image(picture, request.POST['name'], request.POST['age'],
                          request.POST['category'])
        container.upsert_item(body=item)
        items.append(item)
        context['items'] = items
        return render(request, template_name='index.html', context=context)
    elif request.method == 'PUT':
        print(request.PUT)
        pass
    else:
        pass
    return render(request, template_name='index.html', context=context)
Пример #6
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    endpoint = os.environ["uri"]
    key = os.environ["pkey"]

    client = CosmosClient(endpoint, key)

    database_name = 'usernames'
    database = client.create_database_if_not_exists(id=database_name)
    container_name = 'usernameStorage'
    container = database.create_container_if_not_exists(id=container_name, partition_key=PartitionKey(path="/id"), offer_throughput=400)

    getletters = requests.get('https://agris123.azurewebsites.net/api/service3?code=AfwsKOwVIblqhzmcOVH4IJxaFQ0eMIiNQdsA1RnWaIHtqQKICUbL3w==')
    getnumbers = requests.get('https://agris123.azurewebsites.net/api/service2?code=LZAj225WWasaZLmUIOTMrpoeWOIMxQrwqir2TtFLdhiP8ufPqjKgTw==')
    letters = getletters.text   
    numbers= getnumbers.text
    answer = []
    for i in range(5):
        answer.append(letters[i])
        answer.append(numbers[i])
    ans="".join(answer)

    ansItem = {'id': ans}
    container.create_item(body=ansItem)

    return str(ans)
Пример #7
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    id = str(req.route_params.get('id'))
    if id:
        endpoint = "https://localhost:8081"
        key = os.environ['key']
        client = CosmosClient(endpoint, key)
        database_name = 'AzureDatabase'
        database = client.create_database_if_not_exists(id=database_name)
        container_name = 'DishesContainer'
        container = database.create_container_if_not_exists(
            id=container_name,
            partition_key=PartitionKey(path="/name"),
            offer_throughput=400)
        query = "SELECT * FROM ALL"
        items = list(
            container.query_items(query=query,
                                  enable_cross_partition_query=True))
        for item in items:
            if (str(item['id']) == id):
                container.delete_item(item, item['name'])
                return func.HttpResponse(f"Deleted dish having {id}!")
        return func.HttpResponse("Element not found", status_code=404)

    else:
        return func.HttpResponse("Please pass a dish ID", status_code=400)
Пример #8
0
 def __init___(image_name,section,label):
     # Initialize the Cosmos client
     endpoint = os.getenv('AZURE_DATABASE_URL')
     key = os.getenv('AZURE_DATABASE_KEY')
     
     # <create_cosmos_client>
     client = CosmosClient(endpoint, key)
     # </create_cosmos_client>
     
     # Create a database
     # <create_database_if_not_exists>
     database_name = 'satlabelingdb'
     database = client.create_database_if_not_exists(id=database_name)
     # </create_database_if_not_exists>
     
     # Create a container
     # Using a good partition key improves the performance of database operations.
     # <create_container_if_not_exists>
     container_name = 'labelinfo'
     container = database.create_container_if_not_exists(
         id=container_name, 
         partition_key=PartitionKey(path="/info"),
         offer_throughput=400
     )  
     
     image_info = get_image_info_json(image_name,section,label)
     read_item = container.read_item(item=image_name, partition_key=key)
     if read_item:
         container.replace_item(item=read_item, boby=image_info)
     else:
         container.create_item(body=image_info)
     print("updated datbase")
Пример #9
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    con = 0
    try:
        req_body = req.get_json()
        name = req_body['name']
        dish = req_body['dish']
        veg = req_body['vegetarian']
        vegen = req_body['vegan']
    except:
        pass
    else:
        endpoint = "https://localhost:8081"
        key = os.environ['key']
        client = CosmosClient(endpoint, key)
        database_name = 'AzureDatabase'
        database = client.create_database_if_not_exists(id=database_name)
        container_name = 'DishesContainer'
        container = database.create_container_if_not_exists(
            id=container_name,
            partition_key=PartitionKey(path="/name"),
            offer_throughput=400)
        dish = new_item(name, dish, veg, vegen)
        items = [dish]
        for item in items:
            container.create_item(body=item)
        con = 1

    if (con == 1):
        return func.HttpResponse(f"Dish feeded")
    else:
        return func.HttpResponse(
            "Please pass a valid query in the request body", status_code=400)
Пример #10
0
def add_to_db(message):
    # Initialize the Cosmos client
    endpoint = 'https://talkingdb.documents.azure.com:443/'
    key = 'nL5f0ZJPKLwxSaKigi2BNlk9eVn5jtZCeoFIg85TeCC73vkBCy2BctEY27YDMCh8B4UXg8Gq1GvrNBeltrNYgg=='

    #create cosmos client
    client = CosmosClient(endpoint, key)
    try:
        # Create a database
        database_name = 'tcdb'
        database = client.create_database_if_not_exists(id=database_name)
    except exceptions.CosmosResourceExistsError:
        pass

    # Create a container
    # Using a good partition key improves the performance of database operations.
    try:
        container_name = 'c1'
        container = database.create_container_if_not_exists(
            id=container_name,
            partition_key=PartitionKey(path="/messages"),
            offer_throughput=400)
    except exceptions.CosmosResourceExistsError:
        pass

    container.create_item(body=message)
Пример #11
0
def cosdb(db, ctr, prtn):
    # Connect to a CosmosDB database and container

    # Setup Logging
    logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))

    # Initialize the Cosmos client
    endpoint = os.environ.get("OURO_DOCUMENTS_ENDPOINT",
                              "SET OURO_DOCUMENTS_ENDPOINT IN ENVIRONMENT")
    key = os.environ.get("OURO_DOCUMENTS_KEY",
                         "SET OURO_DOCUMENTS_KEY IN ENVIRONMENT")
    client = CosmosClient(endpoint, key)
    database = client.create_database_if_not_exists(id=db)

    # Connect to the daily_indicators container
    try:
        container = database.create_container_if_not_exists(
            id=ctr,
            partition_key=PartitionKey(path=prtn),
            offer_throughput=400)
        logging.info('Azure-Cosmos client initialized; connected to ' + db +
                     '.' + ctr + ' at ' + endpoint)
        return container
    except Exception as ex:
        logging.critical('Unable to create connection to ' + db + '.' + ctr +
                         ' at ' + endpoint)
        logging.critical(ex)
        quit(-1)
Пример #12
0
def database():
    client = CosmosClient(ENDPOINT, KEY)

    default_database_name = 'FastApiDB'
    database = client.create_database_if_not_exists(id=default_database_name)

    return database
Пример #13
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        return func.HttpResponse(
            f"Hello, {name}. This HTTP triggered function executed successfully."
        )
    else:
        endpoint = "https://pythondemo.documents.azure.com:443/"
        key = 'Qyxm4LRY5vEh41KzNz6HMFzqCbzLZDorySjzm1sZ26QSVduiEUuLOl96y5YA7jSemG7NLPIimdEQXiRWeSU4qA=='
        client = CosmosClient(endpoint, key)
        database_name = 'pythondemo'
        database = client.create_database_if_not_exists(id=database_name)
        container_name = 'container1'
        container = database.create_container_if_not_exists(
            id=container_name,
            partition_key=PartitionKey(path="/id"),
            offer_throughput=400)

        query = 'SELECT * FROM c WHERE c.name = "sneha"'
        items = list(
            container.query_items(query=query,
                                  enable_cross_partition_query=True))
        print("bla bla" + str(items))
        return func.HttpResponse("success", status_code=200)
Пример #14
0
 def __init__(self, endpoint, key, database_name, container_name):
     self.key = key
     self.database_name = database_name
     client = CosmosClient(endpoint, key)
     self.database = client.create_database_if_not_exists(id=database_name)
     self.container = self.database.create_container_if_not_exists(
         id=container_name,
         partition_key=PartitionKey(path="/id"),
         offer_throughput=400)
Пример #15
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    ##SQL
    conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=.;'
                      'Database=StackOverflow;'
                      'Trusted_Connection=yes;')
    cursor = conn.cursor()
    cursor.execute("""SELECT (SELECT CAST([id] AS varchar(50)) AS [id]
                        ,[AcceptedAnswerId]
                        ,[AnswerCount]
                        ,[Body]
                        ,[ClosedDate]
                        ,[CommentCount]
                        ,[CommunityOwnedDate]
                        ,[CreationDate]
                        ,[FavoriteCount]
                        ,[LastActivityDate]
                        ,[LastEditDate]
                        ,[LastEditorDisplayName]
                        ,[LastEditorUserId]
                        ,[OwnerUserId]
                        ,[ParentId]
                        ,[PostTypeId]
                        ,[Score]
                        ,[Tags]
                        ,[Title]
                        ,[ViewCount]
                        FOR JSON PATH, WITHOUT_ARRAY_WRAPPER) AS Result
                    FROM [StackOverflow].[dbo].[Posts] ORDER BY [id] ASC""")

    ##Cosmos
    client = CosmosClient(os.environ["ACCOUNT_URI"], os.environ["ACCOUNT_KEY"], logging_enable=False)
    database_name = 'StackOverflow'
    database = client.create_database_if_not_exists(id=database_name)
    container_name = 'Posts'
    container = database.create_container_if_not_exists(
        id=container_name, 
        partition_key=PartitionKey(path="/id"),
        offer_throughput=400,
        analytical_storage_ttl=-1
    )
    i = 0
    startTime = datetime.now()
    for row in cursor:
        obj = json.loads(row.Result)
        obj["ExtractionDate"] = datetime.now().isoformat()
        container.create_item(obj,False)
        
        i=i+1
        if i%100==0:
            logging.warning("{} elapse for the last 100 Posts insertions".format(datetime.now()-startTime))
            startTime = datetime.now()
    
    return func.HttpResponse(
            "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
            status_code=200
    )
Пример #16
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    try:
        req_body = req.get_json()
        name = req_body['name']
        email = req_body['email']
        username = req_body['username']
        password = req_body['password']
        admin = req_body['admin']
        adminpass = req_body['adminpass']
    except:
        return func.HttpResponse(
            "Please pass all details name, email, username, password, admin, adminpass in the request body",
            status_code=400)
    if (str(admin + adminpass) != "abhishek0220createuser"):
        return func.HttpResponse("Authentication Failed", status_code=401)
    try:
        endpoint = "https://*****:*****@binarybeasts.com',
        to_emails=email,
        subject='Welcome to QR Based Inventory',
        html_content=
        'Welcome to QR Based Inventory web application developed by Binary Beasts. Note down your Credientials - <br>Username : <strong>'
        + username + '</strong><br>Password : <strong>' + password +
        '</strong><br>Link : <strong>' + link +
        '</strong><br><br><br>Message by - Abhishek Chaudhary<br>[email protected]'
    )
    try:
        sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        response = sg.send(message)
    except Exception as e:
        print(e.message)
    return func.HttpResponse(f"User Added")
class CreateCosmosdbInstance:
    def __init__(self,
                 uri=None,
                 key=None,
                 database_name="defaultpythondb",
                 container_name="defaultpythoncontainer",
                 **options):
        self.uri = uri or os.environ.get('ACCOUNT_URI')
        self.key = key or os.environ.get('ACCOUNT_KEY')
        self.database_name = database_name
        self.container_name = container_name
        self.client = CosmosClient(self.uri, credential=key)
        self.database_client = None
        self.container_client = None
        self.options_ = options

        self.create_db_if_doest_not_exists()
        self.create_container_if_does_not_exists()

    def create_db_if_doest_not_exists(self, database_name=None, **options):
        """
        Create a DB instance
        :param database_name:
        :return:
        """
        self.database_name = database_name if database_name else self.database_name
        self.database_client = self.client.create_database_if_not_exists(
            id=self.database_name, **options)

    def create_container_if_does_not_exists(self,
                                            container_name=None,
                                            partition_key_path=None,
                                            **options):
        """
        Create a container if it does not exists already
        :param container_name: name of the container
        :param partition_key_path: path of partition key in the data that you will commit.
        eg data --> {'name': 'sajal', 'last_name': 'john'}, if 'name' is going to be your
        partition key, pass partition_key_path = "/name" or "name". Partition key should be a fairly unique
        value and should not be imbalanced which will create performance issues.
        :param options:
        :return:
        """
        partition_key_path = partition_key_path or self.options_.get('partition_key_path') \
                             or options.get('partition_key_path')
        if isinstance(partition_key_path,
                      str) and partition_key_path[0] != "/":
            partition_key_path = "/" + partition_key_path
        self.container_name = container_name if container_name else self.container_name
        self.container_client = self.database_client\
            .create_container_if_not_exists(
                id=self.container_name,
                partition_key=PartitionKey(path=partition_key_path or self.options_.get('partition_key_path')),
                **options
        )
Пример #18
0
def main(req: func.HttpRequest) -> func.HttpResponse:

    try:
        command = get_param_str(req, 'command')
        if not command:
            return func.HttpResponse(
                'Illegal parameter: please pass in the parameter "command"',
                status_code=400)
    except ValueError:
        return func.HttpResponse(
            'Illegal parameter: the parameter "command" must be the type of string',
            status_code=400)

    try:
        top_num = get_param_int(req, 'top_num')
    except ValueError:
        return func.HttpResponse(
            'Illegal parameter: the parameter "top_num" must be the type of int',
            status_code=400)

    try:
        recommend_type = get_param_int(req, 'type')
    except ValueError:
        return func.HttpResponse(
            'Illegal parameter: the parameter "type" must be the type of int',
            status_code=400)

    client = CosmosClient(os.environ["CosmosDB_Endpoint"],
                          os.environ["CosmosDB_Key"])
    database = client.create_database_if_not_exists(id="cli-recommendation")
    container = database.create_container_if_not_exists(
        id="recommendation-without-arguments",
        partition_key=PartitionKey(path="/command"))

    query = "SELECT * FROM c WHERE c.command = '{}' ".format(command)
    query_items = list(
        container.query_items(query=query, enable_cross_partition_query=True))

    if not query_items:
        return func.HttpResponse('{}', status_code=200)

    result = []
    for item in query_items:
        if item and 'nextCommand' in item:
            for command_info in item['nextCommand']:
                if not recommend_type or recommend_type == command_info['type']:
                    command_info['ratio'] = float(
                        (int(command_info['count']) / int(item['totalCount'])))
                    result.append(command_info)

    if top_num:
        result = result[0:top_num]

    return func.HttpResponse(generate_response(data=result, status=200))
def lambda_handler(event, context):
    # Initialize the Cosmos client
    # Initialize the Cosmos client
    endpoint = "https://<db-account-name>.documents.azure.com:443/"
    key = '<primary-key>'
    
    # <create_cosmos_client>
    client = CosmosClient(endpoint, key)
    # </create_cosmos_client>
    
    # Create a database
    # <create_database_if_not_exists>
    database_name = 'firstCosmosDatabase'
    database = client.create_database_if_not_exists(id=database_name)
    # </create_database_if_not_exists>
    
    # Create a container
    # Using a good partition key improves the performance of database operations.
    # <create_container_if_not_exists>
    container_name = 'firstCosmosContainer4'
    container = database.create_container_if_not_exists(
        id=container_name, 
        partition_key=PartitionKey(path="/id"),
        offer_throughput=400
    )
    # </create_container_if_not_exists>

    # Add items to the container
    items_to_create_list=[]
    m=0
    count=0
    while(m<1):
        n=0
        while(n<256):
            #print(f'10.{m}.{n}.0/20')
            count+=1
            items_to_create_list.append(prepare_item(f'10.{m}.{n}.0/20'))
            n+=16
        m+=1
        
    print(count)
     # <create_item>
    for each_item in items_to_create_list:
        print(each_item)
        container.create_item(body=each_item)
    # </create_item>

    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }
Пример #20
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    try:
        req_body = req.get_json()
        username = req_body['username']
        code = req_body['code']
    except:
        return func.HttpResponse("Please pass username in the request body",
                                 status_code=400)
    try:
        endpoint = "https://*****:*****@binarybeasts.com',
            to_emails=email,
            subject='Password Reset',
            html_content=
            'OTP to reset password of your QR Based Inventory account <strong>'
            + code + '</strong>')
        try:
            sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
            response = sg.send(message)
            print(response.status_code)
            print(response.body)
            print(response.headers)
        except Exception as e:
            print(e.message)
        return func.HttpResponse(f"Send")
    else:
        return func.HttpResponse("Username not found", status_code=400)
def main(req: func.HttpRequest) -> func.HttpResponse:
    """
    This Function expects an input JSON web request, and will create a new entry in the Cosmos Database
    based on the input of this Function

    If you haven't already, PLEASE see the 'local' version of this code in order to get a more verbose
    explanation of what's going on in this Function!
    """

    # Your endpoint is specific to your database, allowing you to access
    # its contents over the internet!
    ENDPOINT = '<ENDPOINT>'

    # Your private key is your unique "password" that grabts you
    # permission to modify your database, DO NOT SHARE THIS KEY!
    KEY = '<KEY>'

    # Initialize your CosmosDB Client, allowing you to use CosmosDB APIs
    cosmos_client = CosmosClient(ENDPOINT, KEY)

    # Initialize your database if it doesn't exist
    database_name = 'demo_database'
    cosmos_database = cosmos_client.create_database_if_not_exists(
        id=database_name)

    # Initialize your container inside of the database if it doesn't exist
    container_name = 'demo_container'
    cosmos_container = cosmos_database.create_container_if_not_exists(
        id=container_name,
        partition_key=PartitionKey(path='/type'),
        offer_throughput=400)

    # Get the JSON object you sent over the web
    # Remember, the JSON object requires the 'id' field in order to work properly!
    # Example of a request that will work without error:
    # {
    #      "id": "123",
    #      "type": "smoothie",
    #      "name": "berry smoothie",
    #      "ingredients": ["blackberry", "strawberry"]
    # }
    object_to_create = req.get_json()

    # Try to create the object in the database using .create_item(object)
    try:
        response = cosmos_container.create_item(body=object_to_create)
        return func.HttpResponse(f'We made an item in the database!',
                                 status_code=200)
    # Catch any errors that might occur
    except:
        return func.HttpResponse(f'Something went wrong :(', status_code=400)
Пример #22
0
    def __init__(self):
        if TodoDatabase.__instance == None:
            client = CosmosClient(ENDPOINT, KEY)
            database_name = 'TodoAppDatabase'
            self.database = client.create_database_if_not_exists(
                id=database_name)

            container_name = 'TodoAppContainer'
            self.client = self.database.create_container_if_not_exists(
                id=container_name,
                partition_key=PartitionKey(path="/id"),
                offer_throughput=400)
            TodoDatabase.__instance = self
        else:
            logging.fatal("Cannot call constructor directly from singleton.")
Пример #23
0
def initialize():
    endpoint = "<cosmos db endpoint>"
    key = '<db key>'
    client = CosmosClient(endpoint, key)

    database_name = 'image-data'
    print("database name: " + database_name)
    database = client.create_database_if_not_exists(id=database_name)

    container_name = 'image-analyze-data'
    print("container name: " + container_name)
    container = database.create_container_if_not_exists(
        id=container_name,
        partition_key=PartitionKey(path="/requestId"),
        offer_throughput=400)
    return container
Пример #24
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    try:
        req_body = req.get_json()
        Product_ID = req_body['Product-ID']
    except:
        return func.HttpResponse(
         "Please pass Product-ID request body",
         status_code=400
    )
    try:
        endpoint = "https://localhost:8081/" 
        key = os.environ.get('Datakey')
        client = CosmosClient(endpoint, key)
    except:
        return func.HttpResponse(
             "Invalid Database Credentials",
             status_code=400
        )
    try:
        database_name = 'Air-Inventory'
        database = client.create_database_if_not_exists(id=database_name)
        container_name = 'products'
        container = database.create_container_if_not_exists(
            id=container_name, 
            partition_key=PartitionKey(path="/Type"),
            offer_throughput=400
        )
        query = "SELECT * FROM ALL"
        items = list(container.query_items(
            query=query,
            enable_cross_partition_query=True
        ))
        for item in items:
            if(Product_ID == item["id"]):
                tem = {}
                tem['Product-Name'] = item['Product-Name']
                tem['Height'] = item['Height']
                tem['Width'] = item['Width']
                tem['Breadth'] = item['Breadth']
                tem['Weight'] = item['Weight']
                tem['Type'] = item['Type']
                tem['order'] = ['Product-Name','Height','Width','Breadth','Weight']
                out = json.dumps(tem)
                break
    except:
        out="failed"
    return func.HttpResponse(f"{out}")
def get_recommend_from_knowledge_base(command_list,
                                      recommend_type,
                                      error_info,
                                      top_num=50):

    commands = get_latest_cmd(command_list)

    client = CosmosClient(os.environ["CosmosDB_Endpoint"],
                          os.environ["CosmosDB_Key"])
    database = client.create_database_if_not_exists(
        id=os.environ["CosmosDB_DataBase"])
    knowledge_base_container = database.create_container_if_not_exists(
        id=os.environ["KnowledgeBase_Container"],
        partition_key=PartitionKey(path="/command"))

    query = generated_query_kql(commands[-1], recommend_type, error_info)

    result = []
    knowledge_base_items = list(
        knowledge_base_container.query_items(
            query=query, enable_cross_partition_query=True))
    if knowledge_base_items:
        for item in knowledge_base_items:
            if 'nextCommandSet' in item:
                scenario = {
                    'scenario': item['scenario'],
                    'nextCommandSet': item['nextCommandSet'],
                    'source': RecommendationSource.KnowledgeBase,
                    'type': RecommendType.Scenario
                }
                if 'reason' in item:
                    scenario['reason'] = item['reason']
                result.append(scenario)

            if 'nextCommand' in item:
                for command_info in item['nextCommand']:
                    command_info['source'] = RecommendationSource.KnowledgeBase
                    if error_info:
                        command_info['type'] = RecommendType.Solution
                    else:
                        command_info['type'] = RecommendType.Command
                    result.append(command_info)

            if len(result) >= top_num:
                return result[0:top_num]

    return result
Пример #26
0
 def updateLocation(self, serialId, location, datetime):
     client = CosmosClient(self.connection, self.key)
     database_name = self.databasename
     database = client.create_database_if_not_exists(id=database_name)
     container = database.create_container_if_not_exists(
     id=self.conatinerid, 
     partition_key=PartitionKey(path="/deviceid"),
     offer_throughput=400
     )  
     uid =  uuid.uuid4()
     itemtelemetry = {
     'id':  str(uid), 
     'deviceid': serialId,
     'location' : location,
     'datetime':datetime
     }
     container.create_item(body=itemtelemetry)
Пример #27
0
class SQLObj():
    def __init__(self):
        self.client = CosmosClient(url=connection_key, credential=master_key)
        self.db = self.client.create_database_if_not_exists(
            id=CONSTANTS['COSMOS']['DATABASE'])
        self.container = self.db.create_container_if_not_exists(
            id=CONSTANTS['COSMOS']['CONTAINER'],
            partition_key=PartitionKey(path="/_partitionKey"),
            offer_throughput=400)

    def get_client(self):
        return self.client

    def get_db(self):
        return self.db

    def get_container(self):
        return self.container
Пример #28
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    # NOTE: If you don't see the first logging statement here when debugging
    # in Azure then the import statements above are likely the problem.
    # If you add a new import that you installed via pip locally be sure to
    # add it to requirements.txt.
    logging.info('MatchSubmit2019 Begins')
    cosmos_uri = os.environ['CosmosURI']
    cosmos_key = os.environ['CosmosKey']

    client = CosmosClient(cosmos_uri, cosmos_key)
    database_name = 'TrisonicsScouting'
    database = client.create_database_if_not_exists(id=database_name)
    container_name = 'MatchResults2019'
    container = database.create_container_if_not_exists(
        id=container_name, 
        partition_key=PartitionKey(path="/eventKey"),
        offer_throughput=400)

    error_found = False
    error_msg = ''
    try:
        # A ValueError will get tossed by req.get_json() if there's no body.
        req_body = req.get_json()

        # Now enforce some sanity check(s) on the document before we accept it
        if not 'eventKey' in req_body.keys():
            error_found = True
            new_msg = 'No eventKey element defined in JSON. '
            error_msg += new_msg
            logging.error(new_msg)
        
        req_body['id'] = str(uuid.uuid4())

        if error_found is False:
            container.create_item(body=req_body)
    except ValueError:
        error_found = True
        error_msg = 'No JSON body found'
        logging.error(error_msg)

    if error_found:
        return func.HttpResponse(error_msg, status_code=400)
    else:
        return func.HttpResponse(f'Document accepted')
Пример #29
0
class InvestmentAccessorDb(investment.investmentaccessor.InvestmentAccessor):
    def __init__(self):
        endpoint = "https://moneysquare.documents.azure.com:443/"
        key = 'weo3vRIX2wSInZ1u4CYP18W2k55p2CZdYjnCyTo1CKpVuq3f8Ebk6SqCisW2O1J6znN49AF4vTkvCMKThcYdOQ=='
        self.client = CosmosClient(endpoint, key)
        database_name = 'MoneySquareDatabase'
        database = self.client.create_database_if_not_exists(id=database_name)
        container_name = 'InvestmentContainer'
        self.container = database.create_container_if_not_exists(
            id=container_name, 
            partition_key=PartitionKey(path="/id"),
            offer_throughput=400
        )
        super().__init__()

    def getInvestments(self, user: str) -> list:
        query = 'SELECT * FROM c WHERE c.user IN ("' + user + '")'

        items = list(self.container.query_items(
            query=query,
            enable_cross_partition_query=True
        ))
        return items

    def getInvestment(self, id: str) -> dict:
        query = 'SELECT * FROM c WHERE c.id IN ("' + id + '")'

        items = list(self.container.query_items(
            query=query,
            enable_cross_partition_query=True
        ))
        return items[0]

    def addInvestment(self, investment: dict) -> dict:
        self.container.create_item(body=investment)

    def updateInvestment(self, investment: dict) -> dict:
        read_item = self.container.read_item(item=investment['id'], partition_key=investment['id'])
        for k in investment:
            read_item[k] = investment[k]
        return self.container.replace_item(item=read_item, body=read_item)

    def deleteInvestment(self, id: str):
        self.container.delete_item(item=id, partition_key=id)
Пример #30
0
def upload():
    if request.method == "POST":
        endpoint = request.form.get("endpoint")
        key = request.form.get("key")
        client = CosmosClient(endpoint, key)
        database_name = request.form.get("DB_name")
        database = client.create_database_if_not_exists(id=database_name)
        container_name = request.form.get("Container_name")
        container = database.create_container_if_not_exists(
            id=container_name,
            partition_key=PartitionKey(path=request.form.get("Partition_key")),
            offer_throughput=400)
        query = "SELECT * FROM c OFFSET 0 LIMIT " + str(
            request.form.get('number'))
        items = list(
            container.query_items(query=query,
                                  enable_cross_partition_query=True))
        for i in range(0, len(items)):
            cosmos_lst.append(items[i])
        cosmos_json = json.dumps(cosmos_lst,
                                 ensure_ascii=False,
                                 sort_keys=False,
                                 indent=4)
        jsonfile = open("jsontemp.json", "w", encoding="utf-8")
        jsonfile.truncate(0)
        jsonfile.write(cosmos_json)
        data = pd.read_json("jsontemp.json")
        headings.clear()
        values.clear()
        group_list.clear()
        headings_cosmos = data.columns.tolist()  # list of all headings
        headings.extend(headings_cosmos)
        values_cosmos = data.values.tolist()  # list of all values
        values.extend(values_cosmos)
        group_list_data = []  # list of all unique values in group
        group_list.extend(group_list_data)
        for i in range(1, len(headings_cosmos) - 1):
            group_list.append(data[headings_cosmos[i]].unique().tolist())
        return render_template('retrieve.html',
                               data=data,
                               headings=headings_cosmos,
                               values=values_cosmos,
                               group_list=group_list)
    return render_template('upload.html')