Skip to content
Snippets Groups Projects
Commit b1b3fa55 authored by aj3g19's avatar aj3g19
Browse files

added azure funtion folders

parent f125005d
Branches
No related tags found
No related merge requests found
Showing
with 512 additions and 0 deletions
import logging
import json
import azure.functions as func
from azure.cosmos.exceptions import CosmosHttpResponseError
import azure.cosmos.cosmos_client as cosmos_client
import os
import config
HOST = config.settings['host']
MASTER_KEY = config.settings['master_key']
DATABASE_ID = config.settings['database_id']
CONTAINER_ID = config.settings['chat_info_container_id']
client = cosmos_client.CosmosClient(HOST,credential=MASTER_KEY)
database = client.get_database_client(DATABASE_ID)
container = database.get_container_client(CONTAINER_ID)
#need to check type of inputs
#input = name: String, members: userID(s), admins: userID(s)
#fields = name, memberIDs, admins
#admin must be member
#return Id of created chat
def main(req: func.HttpRequest,chatinfo: func.Out[func.Document]) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
json_given = req.get_json()
if 'members' not in json_given or ('admins' not in json_given) or ('name' not in json_given):
return func.HttpResponse("Missing JSON key")
max_id = 0
prompts_query = "SELECT TOP 1 * FROM ChatInfo ORDER BY ChatInfo.ChatID DESC"
for item in container.query_items(query=prompts_query,enable_cross_partition_query=True):
logging.info(item["ChatID"])
if item["ChatID"] > max_id:
max_id = item["ChatID"]
new_id = max_id + 1
dict_out = {}
dict_out['ChatID'] = new_id
dict_out['name'] = json_given['name']
dict_out['members'] = json_given['members']
dict_out['admins'] = json_given['admins']
try:
chatinfo.set(func.Document.from_dict(dict_out))
json_out = {
'result' : True,
'chatId' : new_id
}
return func.HttpResponse(json.dumps(json_out))
except CosmosHttpResponseError:
return func.HttpResponse("An error has occured")
\ No newline at end of file
{
"scriptFile": "__init__.py",
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "$return"
},
{
"type": "cosmosDB",
"direction": "out",
"name": "chatinfo",
"databaseName": "UsersDB",
"collectionName": "ChatInfo",
"createIfNotExists": "false",
"connectionStringSetting": "usersdb"
}
]
}
{
"name": "Azure"
}
\ No newline at end of file
import logging
import json
import azure.functions as func
from azure.cosmos.exceptions import CosmosHttpResponseError
#takes in memberID
#returns chatID of chats the member is in
def main(req: func.HttpRequest,documents: func.DocumentList) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
json_given = req.get_json()
if 'memberID' not in json_given:
return func.HttpResponse("Missing JSON key")
memID = json_given['memberID']
chatIDs = []
#go through each chat and find memberID
for document in documents:
if(memID in document["members"]):
chatIDs.append(document["ChatID"])
return func.HttpResponse(json.dumps(chatIDs))
{
"scriptFile": "__init__.py",
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get"
]
},{
"type": "cosmosDB",
"direction": "in",
"name": "documents",
"databaseName": "UsersDB",
"collectionName": "ChatInfo",
"createIfNotExists": "false",
"connectionStringSetting": "usersdb"
} ,
{
"type": "http",
"direction": "out",
"name": "$return"
}
]
}
{
"name": "Azure"
}
\ No newline at end of file
import logging
import config
import azure.functions as func
import json
import azure.cosmos.cosmos_client as cosmos_client
import os
HOST = config.settings['host']
MASTER_KEY = config.settings['master_key']
DATABASE_ID = config.settings['database_id']
CONTAINER_ID = config.settings['chat_messages_container_id']
client = cosmos_client.CosmosClient(HOST,credential=MASTER_KEY)
database = client.get_database_client(DATABASE_ID)
container = database.get_container_client(CONTAINER_ID)
#input ChatID, return last message
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
json_given = req.get_json()
if 'ChatID' not in json_given:
return func.HttpResponse("Missing JSON key")
ChatID = json_given['ChatID']
prompt_query = "SELECT TOP 1 ChatMessages.username, ChatMessages.message, ChatMessages.date,"
prompt_query+= "ChatMessages.time FROM ChatMessages WHERE ChatMessages.ChatID = " + str(ChatID)
prompt_query+= " ORDER BY ChatMessages.date ASC,ChatMessages.time ASC"
items_out = []
for item in container.query_items(query=prompt_query,enable_cross_partition_query=True):
new_dict = {
"username":item['username'],
"message":item['message'],
"date":item['date'],
"time":item['time']
}
items_out.append(new_dict)
if(len(items_out) == 1):
return func.HttpResponse(json.dumps(items_out[0]))
else:
return func.HttpResponse("error")
{
"scriptFile": "__init__.py",
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get"
]
},
{
"type": "http",
"direction": "out",
"name": "$return"
}
]
}
{
"name": "Azure"
}
\ No newline at end of file
import logging
import config
import azure.functions as func
import json
import azure.cosmos.cosmos_client as cosmos_client
import os
HOST = config.settings['host']
MASTER_KEY = config.settings['master_key']
DATABASE_ID = config.settings['database_id']
CONTAINER_ID = config.settings['chat_messages_container_id']
client = cosmos_client.CosmosClient(HOST,credential=MASTER_KEY)
database = client.get_database_client(DATABASE_ID)
container = database.get_container_client(CONTAINER_ID)
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
json_given = req.get_json()
if 'ChatID' not in json_given:
return func.HttpResponse("Missing JSON key")
ChatID = json_given['ChatID']
prompt_query = "SELECT * FROM ChatMessages WHERE ChatMessages.ChatID = " + str(ChatID)
prompt_query+= " ORDER BY ChatMessages.date ASC, ChatMessages.time ASC"
items_out = []
for item in container.query_items(query=prompt_query,enable_cross_partition_query=True):
new_dict = {
"username":item['username'],
"message":item['message'],
"date":item['date'],
"time":item['time']
}
items_out.append(new_dict)
return func.HttpResponse(json.dumps(items_out))
\ No newline at end of file
{
"scriptFile": "__init__.py",
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get"
]
},
{
"type": "http",
"direction": "out",
"name": "$return"
}
]
}
{
"name": "Azure"
}
\ No newline at end of file
import logging
import json
import azure.functions as func
from azure.cosmos.exceptions import CosmosHttpResponseError
from datetime import datetime
#could check if user is in chat
#atm it takes in just a username and message then stores this in the database
def main(req: func.HttpRequest,messages: func.Out[func.Document]) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
input_json = req.get_json()
#or date or time
if 'username' not in input_json or ('message' not in input_json) or ('ChatID' not in input_json):
return func.HttpResponse("Missing JSON key")
func.HttpResponse.mimetype = 'application/json'
func.HttpResponse.charset = 'utf-8'
#get username and password from json
username = input_json['username']
message = input_json['message']
date = input_json['date']
time = input_json['time']
ChatID = input_json['ChatID']
new_dict = {}
new_dict['username'] = username
new_dict['message'] = message
new_dict['ChatID'] = ChatID
new_dict['date'] = date
new_dict['time'] = time
try:
messages.set(func.Document.from_dict(new_dict))
json_out = {
'result' : True,
'msg':'OK'
}
return func.HttpResponse(json.dumps(json_out))
except CosmosHttpResponseError:
return func.HttpResponse("An error has occured")
{
"scriptFile": "__init__.py",
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"post"
]
},
{
"type": "cosmosDB",
"direction": "out",
"name": "messages",
"databaseName": "UsersDB",
"collectionName": "ChatMessages",
"createIfNotExists": "false",
"connectionStringSetting": "usersdb"
},
{
"type": "http",
"direction": "out",
"name": "$return"
}
]
}
{
"name": "Azure"
}
\ No newline at end of file
import config
import json
import azure.functions as func
import azure.cosmos.cosmos_client as cosmos_client
HOST = config.settings['host']
MASTER_KEY = config.settings['master_key']
DATABASE_ID = config.settings['database_id']
CONTAINER_ID = config.settings['users_container_id']
client = cosmos_client.CosmosClient(HOST,credential=MASTER_KEY)
database = client.get_database_client(DATABASE_ID)
container = database.get_container_client(CONTAINER_ID)
def main(req: func.HttpRequest) -> func.HttpResponse:
data = req.get_json()
if 'username' not in data or ('password' not in data):
return func.HttpResponse("Missing JSON key")
user_to_authenticate = data['username']
user = None
for item in container.query_items(
query='SELECT * FROM users WHERE users.username = "' + user_to_authenticate + '"',
enable_cross_partition_query=True):
user = item
func.HttpResponse.mimetype = 'application/json'
func.HttpResponse.charset = 'utf-8'
# Check if password mateches with the one stored in the db or if user exists
if user is None or (data['password'] != user['password']):
json_out = {
'result': False,
'msg': 'Username or password incorrect'
}
return func.HttpResponse(json.dumps(json_out))
else:
json_out = {
'result': True,
'msg': 'OK'
}
return func.HttpResponse(json.dumps(json_out))
\ No newline at end of file
{
"scriptFile": "__init__.py",
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get"
]
},
{
"type": "http",
"direction": "out",
"name": "$return"
}
]
}
import json
import azure.functions as func
from azure.cosmos.exceptions import CosmosHttpResponseError
def main(req: func.HttpRequest, document: func.DocumentList, users: func.Out[func.Document]) -> func.HttpResponse:
user = req.get_json()
if 'username' not in user or ('password' not in user):
return func.HttpResponse("Missing JSON key")
all_users = []
for p in document:
all_users.append(p['username'])
func.HttpResponse.mimetype = 'application/json'
func.HttpResponse.charset = 'utf-8'
if len(user['username']) < 4:
json_out = {
'result': False,
'msg': 'Username less than 4 characters'
}
return func.HttpResponse(json.dumps(json_out))
elif len(user['username']) > 16:
json_out = {
'result': False,
'msg': 'Username more than 16 characters'
}
return func.HttpResponse(json.dumps(json_out))
elif user['username'] in all_users:
json_out = {
'result': False,
'msg': 'Username already exists'
}
return func.HttpResponse(json.dumps(json_out))
if len(user['password']) < 8:
json_out = {
'result': False,
'msg': 'Password less than 8 characters'
}
return func.HttpResponse(json.dumps(json_out))
elif len(user['password']) > 24:
json_out = {
'result': False,
'msg': 'Password more than 24 characters'
}
return func.HttpResponse(json.dumps(json_out))
try:
user['games_played'] = 0
user['total_score'] = 0
users.set(func.Document.from_dict(user))
json_out = {
'result': True,
'msg': 'OK'
}
return func.HttpResponse(json.dumps(json_out))
except CosmosHttpResponseError:
return func.HttpResponse("Cosmos DB error")
\ No newline at end of file
{
"scriptFile": "__init__.py",
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "$return"
},
{
"type": "cosmosDB",
"direction": "out",
"name": "users",
"databaseName": "UsersDB",
"collectionName": "Users",
"createIfNotExists": "false",
"connectionStringSetting": "usersdb"
},
{
"type": "cosmosDB",
"direction": "in",
"name": "document",
"databaseName": "UsersDB",
"collectionName": "Users",
"createIfNotExists": "false",
"connectionStringSetting": "usersdb"
}
]
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment