Skip to content

Commit

Permalink
Initial commit after moving from Brian's repository
Browse files Browse the repository at this point in the history
  • Loading branch information
jonr667 committed Oct 13, 2020
1 parent 5224125 commit 90ca3e2
Show file tree
Hide file tree
Showing 20 changed files with 1,279 additions and 0 deletions.
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# assett_flask

## Other usefull Ubuntu tools
`sudo apt install build-essential`

## Use Python3 to make venv and install Flask:
`git clone this`
`cd this`
`mkdir venv`
`python3 -m venv venv`
`. venv/bin/activate`
`pip3 install wheel`
`pip3 install Flask flask_pymongo requests-toolbelt`
```
Failed building wheel for MarkupSafe
Running setup.py clean for MarkupSafe
Failed to build MarkupSafe
Installing collected packages: itsdangerous, Werkzeug, click, MarkupSafe, Jinja2, Flask
Running setup.py install for MarkupSafe ... done
Successfully installed Flask-1.1.1 Jinja2-2.11.1 MarkupSafe-1.1.1 Werkzeug-1.0.0 click-7.0 itsdangerous-1.1.0
```
#### To exit venv
`deactivate`

## Basic working example with Flask is run to be seen externally by
```
$ export FLASK_APP=flaskr
$ export FLASK_ENV=development
$ flask init-db
$ flask run
```

## Useful examples
#### Authentication: https://github.com/pallets/flask/tree/master/examples/tutorial/flaskr
204 changes: 204 additions & 0 deletions asset_tracker_restapi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
from jira_requests import jira_requests
import json
import pprint


class asset_tracker_restapi:
def __init__(self, username=None, password=None):
self.my_request = jira_requests(username=username, password=password)

def add_asset(self, asset_dict):
# This is only for testing, it was used to generate a large number of items
json_dict = {'objectTypeId': asset_dict['object_type_id'],
# 'categoryName': item_dict['category'],
'attributes': [
{'objectTypeAttributeId': 2, 'objectAttributeValues': [{'value': asset_dict['asset_name']}]},
# {'objectTypeAttributeId': item_dict[''], 'value': [item_dict['asset_name']]},
{'objectTypeAttributeId': 5, 'objectAttributeValues': [{'value': asset_dict['tracking_hist']}]}, # Tracking Hist
{'objectTypeAttributeId': 6, 'objectAttributeValues': [{'value': asset_dict['rad_info']}]}, # Tracking Hist
# {'typeName': 'system.description', 'values': [item_dict['asset_desc']]},
{'objectTypeAttributeId': 7, 'objectAttributeValues': [{'value': True}]}
# {'typeName': 'nexo.asset.shipping.origin', 'values': [item_dict['origin']]},
# {'typeName': 'nexo.asset.image', 'values': [item_dict['asset_image']]}
]
}
#print(json_dict)
inserted_asset = self.my_request.post_data("object/create", json_dict)
print(inserted_asset.json())
return inserted_asset

def upload_file_to_object(self, asset_id, file_object, comment):
# Upload a file to an asset/object with a comment
operator = "attachments/object/" + str(asset_id)
file_added = self.my_request.post_file_upload(operator, file_object, comment)
return asset_id

def get_file_from_object(self, asset_id, file_url):
# Request a single file from an asset
response = self.my_request.get_data_file_url(file_url)
return response

def get_asset_attachments(self, asset_id):
# Get a list of all file attachments the asset has
asset_attachments = self.my_request.get_data("attachments/object/%s" % str(asset_id))
return asset_attachments.json()

def build_json_assets_dict(self, asset_dict):
# This builds up the json for creating or updating an object/asset from a dict of attributes.
json_dict = {}
attribute_list = []
json_dict.update({'objectTypeId': asset_dict['object_type_id']})
for asset_attribute in asset_dict: # Iterate though all the attributes so we can bunch them together into a dict of value lists
if asset_attribute != "object_id" and asset_attribute != "object_type_id":
attribute_id = self.get_attribute_id_from_name(asset_dict['object_type_id'], asset_attribute)
attribute_list.append({'objectTypeAttributeId': attribute_id, 'objectAttributeValues': [{'value': asset_dict[asset_attribute]}]})
json_dict.update({'attributes': attribute_list})
return json_dict

def add_asset_from_dict(self, asset_dict):
# Add an asset, this is processed via a form dictionary with the appropriate information for the object schema
json_dict = self.build_json_assets_dict(asset_dict)
# Inserts are run through a POST request
inserted_asset = self.my_request.post_data("object/create", json_dict).json()
return inserted_asset['id']

def update_asset_from_dict(self, asset_dict):
# Update an asset via a dict that is passed in from a form
json_dict = self.build_json_assets_dict(asset_dict)
# Updates are required to go through a PUT request
updated_asset = self.my_request.put_data("object/%s" % str(asset_dict['object_id']), json_dict).json()
return updated_asset['id']

def get_attribute_id_from_name(self, object_type_id, attribute_name):
# If we pass an attribute name then we can get it's corresponding ID
attribute_dict = self.get_object_type_attributes(object_type_id)
for attribute in attribute_dict:
if attribute['name'] == attribute_name:
return attribute['id']
print("Could not find attribute id for attribute name : %s" % attribute_name)
return 0

def get_object_types_for_schema(self, schema_id):
# Get all available object types / catagories for assets that are under a specific scehma
object_types = self.my_request.get_data("objectschema/%s/objecttypes/flat" % str(schema_id))
return self.parse_object_types_list(object_types)

def parse_object_types_list(self, response):
object_types_list = []
output = response.json()

for my_object_type in output:
if 'description' not in my_object_type:
my_object_type.update({'description': ""})
object_type_dict = {'id': my_object_type['id'],
'name': my_object_type['name'],
'description': my_object_type['description']}
object_types_list.append(object_type_dict)
return object_types_list

def get_object_type_attributes(self, object_type_id):
object_type_attributes = self.my_request.get_data("objecttype/%s/attributes" % str(object_type_id))
# pprint.pprint(object_type_attributes.json())
if object_type_attributes == 0:
return 0
return self.parse_object_type_attributes(object_type_attributes)

def parse_object_type_attributes(self, response):
object_type_attributes_list = []
output = response.json()

for my_object_attrib in output:
object_type_attributes_dict = {'id': my_object_attrib['id'],
'name': my_object_attrib['name'],
'hidden': my_object_attrib['hidden'],
'editable': my_object_attrib['editable'],
'field_type': my_object_attrib['defaultType']['name'],
'options': my_object_attrib['options'].split(',')}
if 'description' in my_object_attrib:
object_type_attributes_dict.update({'description': my_object_attrib['description']})
object_type_attributes_list.append(object_type_attributes_dict)
return object_type_attributes_list

def search_assets(self, field, search_text):
'''Search for asset using field and value for field as input'''
asset_query = field + '=' + search_text
params_dict = {'query': asset_query}
assets = self.my_request.get_data("search", params_dict)
return assets

def get_asset_field_from_json_by_name(self, entry_name, asset_data, entry_value='value'):
my_entry_value = ""
for entry in asset_data: # asset data is a list of dict's so we need to iterate over to find the Name entry
if entry['name'] == entry_name:
my_entry_value = entry[entry_value]
break
return my_entry_value

def get_asset_object_type_by_id(self, asset_id):
operator = "object" + "/" + str(asset_id)
response = self.my_request.get_data(operator)
if response == 0:
return 0
output = response.json()
return output['objectType']['id']

def get_asset_by_id(self, asset_id):
operator = "object" + "/" + str(asset_id)
asset = self.my_request.get_data(operator)
if asset != 0:
return self.parse_asset(asset)
else:
return 0

def parse_asset(self, response):
'''Take in a response request asset from (JIRA) and parse the data into a single easy to read list of dictionary'''
output = response.json()
asset_list = []
for attribute in output['attributes']:
asset_dict = {'id': attribute['objectTypeAttribute']['id'],
'name': attribute['objectTypeAttribute']['name'],
'editable': attribute['objectTypeAttribute']['editable'],
'field_type': attribute['objectTypeAttribute']['defaultType']['name'],
'value': attribute['objectAttributeValues'][0]['value']
}
if 'description' in attribute['objectTypeAttribute']:
asset_dict.update({'description': attribute['objectTypeAttribute']['description']})
asset_list.append(asset_dict)

return asset_list

def get_object_attribute_history(self, asset_id, object_attribute):
asset_history_list = []
operator = "object" + "/" + str(asset_id) + "/history"
full_asset_hist = self.my_request.get_data(operator).json()
for my_asset_hist in full_asset_hist:
asset_history_dict = {}
if 'affectedAttribute' in my_asset_hist:
if my_asset_hist['affectedAttribute'] == object_attribute:
asset_history_dict.update({'person_fullname': my_asset_hist['actor']['displayName']})
asset_history_dict.update({'person_username': my_asset_hist['actor']['name']})
asset_history_dict.update({'change_date': my_asset_hist['created']})
asset_history_dict.update({'old_value': my_asset_hist['oldValue']})
asset_history_dict.update({'new_value': my_asset_hist['newValue']})
asset_history_list.append(asset_history_dict)
return asset_history_list

def get_asset_connected_tickets(self, asset_id):
operator = "objectconnectedtickets" + "/" + str(asset_id) + "/tickets"
asset_tickets = self.my_request.get_data(operator).json()
return asset_tickets['tickets']

def action_id_to_action(self, action_id):
action = ""
if action_id == 1:
action = "Recieved"
elif action_id == 2:
action = "Shipped"
elif action_id == 3:
action = "Cleaned"
elif action_id == 4:
action = "Out for a beer"
return action

def test(self):
print("Hello!, username is : %s, password is : %s" % (self.my_request.username, self.my_request.password))
73 changes: 73 additions & 0 deletions assets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
from jira_requests import jira_requests
from asset_tracker_restapi import asset_tracker_restapi
import pprint
import json
import random
import string
import sys

def get_random_string(length):
letters = string.ascii_lowercase
result_str = ''.join(random.choice(letters) for i in range(length))
#print("Random string of length", length, "is:", result_str)
return result_str


asset_api = asset_tracker_restapi()
#myjira = jira_requests()

#if myjira.verify_auth() != 0:
# print("Auth Failed!!")
# exit()
#item_dict['object_type_id']
#asset_api.test()
#myjson = myitem.list_catagories()
#print(myjson.json())
#items = myitem.get_all_items_in_catagory("Electrical")
#print(items.json())
#myitems = myitem.parse_multiple_items_into_list(items)
#pprint.pprint(items.json())
my_dict = {'rad_info': 6}
#-----
#for item in range(2000, 500000):
# mydict = {'object_type_id': 1, 'part_name': get_random_string(10), 'tracking_hist': get_random_string(500), 'rad_info': get_random_string(1000)}
# myitem.add_item(item_dict=mydict)
# print("Progress : ", item)
#print(myjira.get_data("item", "").text)
#myitem.
#items = myitem.search_items("id", "10312")
#print(items.json())
#print(items.text)
#items = myitem.get_item_by_id("46")
#pprint.pprint(myitem.get_object_types_for_schema(1))
#pprint.pprint(asset_api.get_object_types_for_schema(schema_id=1))
#pprint.pprint(asset_api.get_object_type_attributes(2))
mydict = {'object_id': 66, 'object_type_id': 2, 'max_volatge': 12000}
issues = asset_api.get_asset_connected_tickets("46")
pprint.pprint(issues)
for issue in issues:
print("-----")
pprint.pprint(issue)
#pprint.pprint(asset_api.update_asset_from_dict(mydict))
#pprint.pprint(asset_api.get_object_attribute_history(66, "max_volatge"))
#pprint.pprint(asset_api.get_attribute_id_from_name(1, "received1"))
#print(myitem.parse_items(items))
#print(items.json())
#pprint.pprint(items.json())
#mine = items.json()
#for something in mine:
# print(something)

#pprint.pprint(mine['attributes'])
#for i in mine['attributes']:
## pprint.pprint(i['objectTypeAttribute'])
# pprint.pprint(i['objectTypeAttribute']['id'])
# print(i['objectTypeAttribute']['editable'])
# pprint.pprint(i['objectTypeAttribute']['name'])
# pprint.pprint(i['objectTypeAttribute']['defaultType']['name'])
# if 'description' in i['objectTypeAttribute']:
# pprint.pprint(i['objectTypeAttribute']['description'])
#
# pprint.pprint(i['objectAttributeValues'][0]['value'])

# print("-----")
10 changes: 10 additions & 0 deletions barcode_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import barcode
from barcode.writer import ImageWriter

def testEan():
EAN = barcode.get_barcode_class('ean13')
ean = EAN(u'5679004263734-001', writer=ImageWriter())
fullname = ean.save('my_ean13_barcode')

testEan()

40 changes: 40 additions & 0 deletions flaskr/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import os
#from jira_requests import jira_requests
#from item_management import item_management
#from asset_tracker_restapi import asset_tracker_restapi
from flaskr import auth, main, asset
from flask import Flask


def create_app(test_config=None):
"""Create and configure an instance of the Flask application."""
app = Flask(__name__, instance_relative_config=True)
UPLOAD_FOLDER = './uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config.from_mapping(SECRET_KEY="dev")

# Limit the maximum size of a file upload, else raise RequestEntityTooLarge exception
app.config['MAX_CONTENT_LENGTH'] = 25 * 1024 * 1024

if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile("config.py", silent=True)
else:
# load the test config if passed in
app.config.update(test_config)

# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass

# apply the blueprints to the app
app.register_blueprint(auth.bp)
app.register_blueprint(main.bp)
app.register_blueprint(asset.bp)
#app.register_blueprint(scan.bp)

app.add_url_rule("/", endpoint="index")

return app
Loading

0 comments on commit 90ca3e2

Please sign in to comment.