Where can i find Oil and Gas well locations and data to import into google maps api?

Can someone help me find out where websites like http://www.drillingedge.com/ and other sites are getting there data from? I’m looking for longitude and latitude of every well and well information.

For example where can i find data like this?

http://www.drillingedge.com/north-dakota/williams-county/wells/anderson-5x-4h/33-105-04709

It has to be on the states website right https://www.dmr.nd.gov/oilgas/ but on well search they do not list the well coordinates only township numbers so i can’t get the exact location of the wells.

On the states website there is subscription service which i think has all the data that comes in excel format but in the terms of service (i put below) it says from what i understand that you can’t charge a subscription service with this data. Is this correct if so, where are these other websites getting there oil and gas well data from?

https://www.dmr.nd.gov/oilgas/subscriptionservice.asp

“Excessive mining of data during normal business hours, any automated data mining activities that adversely affect normal server functions at any time, or any business practices that substantially duplicate OGD subscription services without adequately defraying the costs of providing such data under NDCC 38-08-04.6 may result in suspension of user access to our web site.”

VPS2Day – 1GB KVM starting around $4.35/mo in many locations and more!

The team over at VPS2Day has sent over their second ever offer and we are honored to be able to offer these deals today! They’ve been around for a while, so it should be pretty safe to do business with them, but as always, help your fellow readers out with some reviews if you’ve decided to buy and let us all know what you think.

Their WHOIS is public and they’re a registered company in Frankfurt (Company No: HRB 91418). You can find their legal docs here. They accept PayPal, Bitcoin, Litecoin, PaySafeCard and Credit Cards (VISA/Mastercard) as payment methods.

This offer is available in several locations, including Germany, Netherlands, Romania, United Kingdom, Sweden, Switzerland and Dallas!

A note from the company:

“VPS2day offers powerful yet affordable alternatives to traditional dedicated servers and is highly flexible. Since our founding in 2014, we supply numerous customers from various countries in Europe and around the world. Our focus is on providing stable hosting services in Europe and US.

Contrary to many other providers in the market our team has more than 10 years of experience in hosting and can thus respond to the individual needs of customers. Beside our experience we trust in our in-house development. To obtain the best performance, our host systems are based on the latest technology and only consists enterprise hardware parts. We are monitoring all of our services around the clock!

In addition to our own backend and the enterprise hardware we offer world-class support. We are here 24/7/365 – just for you!

When selecting our data centers, only the best is good enough. We are working with high quality datacenters across Europe with focus on the best networking and redundancy. Of course, we also pay attention to the security of your data: all data centers have a 24/7 monitoring by on-site staff and CCTV camera systems.

Still not convinced? Try our products up to 48 hours for free! If you are not satisfied, we will refund your payment.”

The offer: 

VPS START

  • 1024MB RAM
  • 1x vCPU
  • 25GB SSD Space
  • 100Mbps Connectivity (upgradable)
  • 1x IPv4
  • /48 IPv6
  • KVM
  • 3.85€/mo (around $ 4.35/mo)
  • [ORDER HERE]

VPS BASIC

  • 2048MB RAM
  • 2x vCPU
  • 50GB SSD Space
  • 100Mbps Connectivity (upgradable)
  • 1x IPv4
  • /48 IPv6
  • KVM
  • 7€/mo (around $ 7.91/mo)
  • [ORDER HERE]

Network Info 

Accelerated – Frankfurt, Germany
Test IPv4: 185.44.105.64
Test IPv6: 2a00:f820:24::1
Test file: http://lg-de.vps2day.com/100MB.test
Looking glass: http://lg-de.vps2day.com

Greenhouse Datacenters – The Hague, Netherlands
Test IPv4: 193.242.211.135
Test IPv6: 2001:67c:2ae8:100::1
Test file: http://lg-nl.vps2day.com/100MB.test
Looking glass: http://lg-nl.vps2day.com

M247 – Bucharest, Romania
Test IPv4: 46.108.156.132
Test IPv6: 2A04:9DC0:0:4::1
Test file: http://lg-ro.vps2day.com/100MB.test
Looking glass: http://lg-ro.vps2day.com

M247 – Manchester, United Kingdom
Test IPv4: 89.238.181.126
Test IPv6: 2A02:40:852::1
Test file: http://lg-uk.vps2day.com/100MB.test
Looking glass: http://lg-uk.vps2day.com

Portlane – Stockholm, Sweden
Test IPv4: 109.230.199.10
Test IPv6: 2a00:1a28:1510:9::1
Test file: http://lg-se.vps2day.com/100MB.test
Looking glass: http://lg-se.vps2day.com

Psychz Networks – Dallas (TX), USA
Test IPv4: 45.35.190.3
Test file: http://lg-us.vps2day.com/100MB.test
Looking glass: http://lg-us.vps2day.com

Datasource – Kanton Zug, Switzerland
Test IPv4: 176.10.125.4
Test file: http://lg-ch.vps2day.com/100MB.test
Looking glass: http://lg-ch.vps2day.com

Hardware Info

– 2x Intel Xeon E5-2670 CPU
– 256 GB RAM
– 8x 1TB SSD HDDs
– 2 or 10 Gbps connectivity

The post VPS2Day – 1GB KVM starting around $ 4.35/mo in many locations and more! appeared first on Low End Box.

TruxgoServers – VPS Promo Servers, special offers from 12 different locations!

TruxgoServers has submitted their first ever offer to us recently and we felt the offers looked pretty good! They are offering SSD powered VPS hosting services out of 12 different server locations! They have put the spotlight on two specific promotions today, from their Miami Florida location and their Egypt location!
See all of their VPS Promo Servers here!

Here’s what they had to say: 

“At Truxgo Servers we are committed the best value in the hosting business including Dedicated Servers, Cloud Hosting, Virtual Servers, and colocation. We are operating 9 locations in 3 Continents: Europe,Asia and America.
Truxgo Servers specializes in providing Colocation and Hosting solutions taking the complexity away, and providing end-to-end technology to support your business.
We Have 850 Payment Methods around world. This guarantees the responsibility in the servers and data centers.”

As always, if you order from TruxgoServers, please feel free to comment in the section below and let us know about it!

Here are the offers: 

Egypt VPS Hosting

  • RAM: 500MB
  • Hard Disk: 20GB SSD
  • Traffic: 500GB
  • 1 x IPv4
  • Port Speed: 100MB
  • $ 25.00 USD/3 Months
  • [ORDER HERE]

Miami VPS Hosting

  • RAM: 2GB
  • Hard Disk: 150GB SSD
  • 1 x IPv4
  • Port Speed: 100MB
  • $ 20.00 USD/Month
  • [ORDER HERE]


Specifications:

– INTEL XEON E3-1230-V2

– 100MB – 1 GB Internet Speed

– IPV4 1 to 250 IPS

– OS Linux/Windows

– Full Root & Shell Access (SSH) Or Remote Desk

– DDoS Protection

Please let us know if you have any questions/comments and enjoy!

The post TruxgoServers – VPS Promo Servers, special offers from 12 different locations! appeared first on Low End Box.

Query against multiple locations within single custom post type post

I have a custom post type for “Events” and each event can have a variable amount of “Locations” (lat/lng) which is stored as meta. I need to be able to get “Event” posts based on the bounds of a map.

I have full control over how I store the meta data of the locations for the post but I can’t think of a way to create a meta_query to check against each location within an event to see if it fits within the min/max lat/lng.

Here’s an example of what would work for a single location:

$  args = array(     'post_type' => 'event',     'posts_per_page' => -1,     'meta_query' => array(         'relation' => 'AND',         array(             'key' => 'coords_0_lat',             'value' => array($  lat_min, $  lat_max,             'compare' => 'BETWEEN',             'type' => 'DECIMAL(10,7)'         ),         array(             'key' => 'coords_0_lng',             'value' => array($  lng_min, $  lng_max,             'compare' => 'BETWEEN',             'type' => 'DECIMAL(10,7)'         )     ) ); $  query = new WP_Query($  args); 

But since events can have any amount of locations I can’t really just do coords_0…, coords_1…, coords_2…, etc.

I have found some information on filtering the “posts_where” to change the “where” into a “LIKE” rather than an “=” but from what I understand I don’t think this would work in my case as it wouldn’t keep the lat/lng of a location together. (Infromation here under “4. Sub custom field values”)

Fully Managed VPS & Dedicated Hosting: Multiple Locations!

Tier.Net
Businesses from all over the world depend on us for fast and reliable hosting services.
You can count on us too!

US-owned with offices in New York and Florida, Tier.Net operates in datacenters strategically located throughout the USA and beyond! Experience the top tier of hosting and customer service at Tier.Net! Cutting edge, reliable, and FAST, Tier.Net provides shared, reseller, VPS,…

Fully Managed VPS & Dedicated Hosting: Multiple Locations!

Nginx multiple locations and REACT router

I’ve a react APP in my web server root. And i need to define some locations excluded from react-router i made the Nginx part like this:

server {     listen 80;     listen 443 ssl;      server_name mydomain.com www.mydomain.com;      client_max_body_size 150m;     client_header_timeout 3m;     client_body_timeout 3m;     send_timeout 3m;      gzip on;     gzip_types       text/css       text/javascript       text/xml       text/plain       application/javascript       application/x-javascript       application/json       application/xml       application/rss+xml       application/atom+xml       font/truetype       font/opentype       image/svg+xml;      ssl_certificate /etc/nginx/tls/mydomain.pem; #/ssl4free/full_chain.pem;     ssl_certificate_key /etc/nginx/tls/mydomain.key; #ssl4free/private_key.pem;      access_log /var/log/nginx/frontend.access.log;     error_log /var/log/nginx/fronend.app.error.log;       location / {         root /home/mydomain/frontend;         try_files $  uri @rewrites;     }       location ^~ /files {         alias /home/mydomain/api/public;     }      location /api/ {         proxy_set_header X-Real-IP $  remote_addr;         proxy_set_header X-Forwarded-For $  proxy_add_x_forwarded_for;         proxy_set_header X-NginX-Proxy true;         proxy_set_header X-Forwarded-Proto https;         proxy_set_header Upgrade $  http_upgrade;         proxy_set_header Connection "upgrade";         proxy_ssl_session_reuse off;         proxy_set_header Host $  http_host;         proxy_cache_bypass $  http_upgrade;         proxy_pass http://express_servers;         proxy_redirect off;         access_log /var/log/nginx/api.access.log;         error_log /var/log/nginx/api.error.log;     }      location ^~ /cp  {         alias /home/mydomain/cp;         #try_files $  uri /cp/index.html;         try_files $  uri @cprewrites;     }      location ^~ /blog {         alias /home/mydomain/blog;         index index.php;         #try_files $  uri $  uri/ =404;         try_files $  uri $  uri/ /blog/index.php?$  args;         if (!-e $  request_filename) { rewrite ^ /discover/index.php last; }         #try_files $  uri @blogrewrites;          location ~ \.php$   {            include /etc/nginx/snippets/fastcgi-php.conf;            #fastcgi_split_path_info ^(/blog)(/.*)$  ;            fastcgi_param SCRIPT_FILENAME $  request_filename;            fastcgi_pass unix:/run/php/php7.3-fpm.sock;         }      }       location ^~ /phpmyadmin {         alias /home/mydomain/phpmyadmin;         index index.php;         try_files $  uri $  uri/ =404;          location ~ \.php$   {            include /etc/nginx/snippets/fastcgi-php.conf;            fastcgi_param SCRIPT_FILENAME $  request_filename;            fastcgi_pass unix:/run/php/php7.3-fpm.sock;         }      }      location @rewrites {       rewrite ^(.+)$   /index.html last;     }      location @cprewrites {       rewrite ^(.+)$   /cp/index.html last;     }      location @blogrewrites {       rewrite ^(.+)$   /blog/index.php last;     } } 

every time switching between locations in google chrome, it needs to hard refresh (CTRL+F5) to show right location!

where is my mistake? i can’t find it.

Conflict between REACT router and Nginx locations

I’ve a react APP in my web server root. And i need to define some locations excluded from react-router i made the Nginx part like this:

server {     listen 80;     listen 443 ssl;      server_name mydomain.com www.mydomain.com;      client_max_body_size 150m;     client_header_timeout 3m;     client_body_timeout 3m;     send_timeout 3m;      gzip on;     gzip_types       text/css       text/javascript       text/xml       text/plain       application/javascript       application/x-javascript       application/json       application/xml       application/rss+xml       application/atom+xml       font/truetype       font/opentype       image/svg+xml;      ssl_certificate /etc/nginx/tls/mydomain.pem; #/ssl4free/full_chain.pem;     ssl_certificate_key /etc/nginx/tls/mydomain.key; #ssl4free/private_key.pem;      access_log /var/log/nginx/frontend.access.log;     error_log /var/log/nginx/fronend.app.error.log;       location / {         root /home/mydomain/frontend;         try_files $  uri @rewrites;     }       location ^~ /files {         alias /home/mydomain/api/public;     }      location /api/ {         proxy_set_header X-Real-IP $  remote_addr;         proxy_set_header X-Forwarded-For $  proxy_add_x_forwarded_for;         proxy_set_header X-NginX-Proxy true;         proxy_set_header X-Forwarded-Proto https;         proxy_set_header Upgrade $  http_upgrade;         proxy_set_header Connection "upgrade";         proxy_ssl_session_reuse off;         proxy_set_header Host $  http_host;         proxy_cache_bypass $  http_upgrade;         proxy_pass http://express_servers;         proxy_redirect off;         access_log /var/log/nginx/api.access.log;         error_log /var/log/nginx/api.error.log;     }      location ^~ /cp  {         alias /home/mydomain/cp;         #try_files $  uri /cp/index.html;         try_files $  uri @cprewrites;     }      location ^~ /blog {         alias /home/mydomain/blog;         index index.php;         #try_files $  uri $  uri/ =404;         try_files $  uri $  uri/ /blog/index.php?$  args;         if (!-e $  request_filename) { rewrite ^ /discover/index.php last; }         #try_files $  uri @blogrewrites;          location ~ \.php$   {            include /etc/nginx/snippets/fastcgi-php.conf;            #fastcgi_split_path_info ^(/blog)(/.*)$  ;            fastcgi_param SCRIPT_FILENAME $  request_filename;            fastcgi_pass unix:/run/php/php7.3-fpm.sock;         }      }       location ^~ /phpmyadmin {         alias /home/mydomain/phpmyadmin;         index index.php;         try_files $  uri $  uri/ =404;          location ~ \.php$   {            include /etc/nginx/snippets/fastcgi-php.conf;            fastcgi_param SCRIPT_FILENAME $  request_filename;            fastcgi_pass unix:/run/php/php7.3-fpm.sock;         }      }      location @rewrites {       rewrite ^(.+)$   /index.html last;     }      location @cprewrites {       rewrite ^(.+)$   /cp/index.html last;     }      location @blogrewrites {       rewrite ^(.+)$   /blog/index.php last;     } } 

every time switching between locations in google chrome, it needs to hard refresh (CTRL+F5) to show right location!

where is my mistake? i can’t find it.

Trigger sirens on cameras in remote locations

Web-app summary:

I’m a complete beginner in web development and I made a sample web application that can trigger sirens on security cameras located in remote locations. Here’s the functionality seen by the user:

  1. Go to website and brought to a landing page with a search bar.
  2. Type in the name of a location.
  3. Be shown all the cameras in that location, and next to each camera is a button to trigger its siren.
  4. There is also a button that triggers all the sirens in that location.

Searching for a location:

When the user searches for a location, the back-end routes this query to a function called search_by_jobsite(jobsite). This function establishes a connection with a third-party API and queries a mock database on Zoho.com. The results are processed and then returned to the server to be shown on the front-end.

Triggering a siren:

This is honestly extremely simple. When the button is pressed, the request on the back-end is routed to a function called pulse_siren(camera_name) that just makes a simple HTTP get request to a camera’s static IP address.

My thoughts:

After making this web-app I realized that Django was absolutely overkill since I don’t even have a local database. I’m essentially just using Django as a web-server and routing. Next time I should use something like Flask, but i’m interested in how I can improve my existing code. When making this project I was primarily focused on actually getting this thing up and running and then optimizing. I feel like my views.py file should be turned into most class-based-views (as they’re called in Django), and I read a lot up on this but I wasn’t exactly sure the best way to implement this.

My code: I’m mostly concerned with cleaning up my views.py file and optimizing it for speed since it takes maybe a second to make the API call. I’ve set up a barebones repository with my code: https://github.com/hgducharme/barebones

What the user sees:

Search results page


views.py

### views.py  from django.shortcuts import render, redirect from django.http import JsonResponse from django.core.exceptions import ObjectDoesNotExist from .models import CameraSystem, CameraModel, ControlByWeb, JobSite from django.core import serializers from django.conf import settings from django.contrib import messages import json, ast, requests, pprint from zcrmsdk import ZCRMRecord, ZCRMRestClient, ZCRMModule, ZCRMException  def siren_search(request):      # Define the term in the search     term = request.GET.get('query', '').strip().lower()     context = {'term': term}      # Handle the AJAX search     if 'query' in request.GET and request.is_ajax():         try:             cameras = CameraSystem.objects.filter(site__name__icontains=term)             json_response = serializers.serialize('json', cameras, fields=(                 'asset_name', 'site',), use_natural_foreign_keys=True, use_natural_primary_keys=True)             parsed = json.loads(json_response)             print(json.dumps(parsed, indent=4, sort_keys=True))          except ObjectDoesNotExist:             return JsonResponse({'success': False}, status=400)          return JsonResponse(json_response, safe=False, status=200)      # Handle when the user presses enter     elif 'query' in request.GET and term != '' and not request.is_ajax():          try:             # Get the list of active raptor cameras at the desired jobsite             deployed = search_zoho(term)              # Sort the list so they show up in HTML as: PANTHER1, PANTHER2, PANTHER3, ..., etc. with 'N/A' at the end             context = {                 'cameras': sorted(deployed, key=lambda camera: (camera['site_id'] == 'N/A', camera['site_id']) ),                 'term': term             }          # Catch any error that the Zoho API might output         except ZCRMException as error:              # If Zoho didn't find any results             if error.status_code == 400 or error.status_code == 204:                 pass             else:                 errorString = f'There was an error with accessing Zoho: {error}'                 messages.add_message(request, messages.INFO, errorString)             pass          return render(request, 'siren_search.html', context)      # Handle when the user presses a siren button for just one camera     elif 'pulse-siren' in request.GET:          # Get the current url so the we can show the same search results after they press the button         redirect_url = request.GET.get('current-url')         asset_name = request.GET.get('pulse-siren').upper()          # Pulse the siren on the desired camera, and for anything that happens add a message to the redirect         try:             response = pulse_siren(asset_name)             response.raise_for_status()             messages.add_message(request, messages.INFO, f"Successful for {asset_name}.")          except requests.exceptions.HTTPError as error:             if response.status_code == 401:                 errorString = f'Looks like {asset_name} is online, but the system was not able to log in.'                 messages.add_message(request, messages.INFO, errorString)             else:                 errorString = f'HTTP error for {asset_name}: {error}'                 messages.add_message(request, messages.INFO, errorString)             pass          except requests.exceptions.ConnectionError as error:             errorString = f'The system failed to connect to {asset_name}. Check to see if the unit is online. If it is, then then the system may have used a wrong username/password.'             messages.add_message(request, messages.INFO, errorString)             pass          except requests.exceptions.Timeout as error:             errorString = f'Timeout error for {asset_name}: the system tried to connect for three seconds but failed.'             messages.add_message(request, messages.INFO, errorString)             pass          except requests.exceptions.RequestException as error:             errorString = f'Oops, something weird happened for {asset_name}: {error}'             messages.add_message(request, messages.INFO, errorString)             pass          return redirect(redirect_url)      # Handle when the user wants to trigger all sirens     elif 'pulse-all-sirens' in request.GET:          # Get the cameras and the redirecut url         redirect_url = request.GET.get('current-url')         camera_json = request.GET.get('pulse-all-sirens')         # for some reason json.loads() doesn't work, so use literal_eval ()         camera_list = ast.literal_eval(camera_json)          # Pulse the siren for each camera on the search results page         for camera in camera_list:             asset_name = camera['asset_name']              # Pulse the siren on the desired camera, and for anything that happens add a message to the redirect             try:                 response = pulse_siren(asset_name)                 response.raise_for_status()                 messages.add_message(request, messages.INFO,                                      f"Successful for {asset_name}.")              except requests.exceptions.HTTPError as error:                 errorString = f'HTTP error for {asset_name}: {error}'                 messages.add_message(request, messages.INFO, errorString)                 pass              except requests.exceptions.ConnectionError as error:                 errorString = f'The system failed to connect for {asset_name}: Check to see if the unit is online, but the system may have used a wrong username/password.'                 messages.add_message(request, messages.INFO, errorString)                 pass              except requests.exceptions.Timeout as error:                 errorString = f'Timeout error for {asset_name}: The system tried to connect for one and a half seconds but failed.'                 messages.add_message(request, messages.INFO, errorString)                 pass              except requests.exceptions.RequestException as error:                 errorString = f'Oops, something weird happened for {asset_name}: {error}'                 messages.add_message(request, messages.INFO, errorString)                 pass          return redirect(redirect_url)      else:         return render(request, 'siren_search.html', context)    ### How can this API call be optimized? Maybe caching or doing something with the session? def search_zoho(jobsite):      # Initialize the API client and search for cameras with a jobsite that matches the search     # This must be in uppercase because the sites on ZOHO are all uppercase     jobsite = jobsite.upper()     config = settings.ZOHO_CONFIG     client = ZCRMRestClient.initialize(config)     all_cameras = ZCRMModule.get_instance('Vendors').search_records(f'{jobsite}')      # Iterate over each returned camera     deployed_cameras = []     for camera_record in all_cameras.data:          # Get properties about the camera to filter results         camera = camera_record.field_data         status = (camera['Status'].lower() if 'Status' in camera else 'None')         camera_type = (camera['Type'].lower() if 'Type' in camera else 'None')         site = (camera['Site']['name'].upper() if 'Site' in camera else 'None')          # Only get the cameras that are deployed at the jobsite of type 'raptor'         if site == jobsite and camera_type == 'raptor':              # Get properties if they exist, else set the default to 'None'             asset_name = (camera['Vendor_Name'].upper() if 'Vendor_Name' in camera else 'N/A' )             site_id = (camera['Multiple_Assets'].upper() if 'Multiple_Assets' in camera else 'N/A')              # Append this camera's dictionary to the list of deployed cameras             temp_dictionary = {'asset_name': asset_name, 'site_id': site_id, 'site': site.capitalize()}             deployed_cameras.append(temp_dictionary.copy())      return deployed_cameras  def pulse_siren(asset_name):      # Configure the url for the desired camera     camera_url = 'http://' + asset_name.lower() + settings.CAMERA_URL + settings.PULSE_SIREN_HALF_SECOND # TODO: I'm using 0.5 seconds right now so I don't annoy the office      # Pulse the siren on the camera for the preset time     username = settings.RAPTOR_AUTHENTICATION['username']     password = settings.RAPTOR_AUTHENTICATION['password']     pulseSiren = requests.get(camera_url, auth=(username, password), timeout=2)     return camera_url 

siren_search.html

{% extends "base.html" %} {% load staticfiles %}  {% block page_title %} Siren System {% endblock %}  {% block styles %} <link href="{% static 'css/camera_search.css' %}" rel="stylesheet"> {% endblock %}   {% block search_title %} <h3>Siren system</h3> {% endblock %}  {% block search_form %} <form id="searchform" action="{% url 'camera_search:siren_search' %}" method="GET">     <div class="input-group">         <input id="searchbar" name="query" autocomplete="on" onkeyup=getCameras(this.value)             placeholder="Search for the name of a jobsite." class="form-control" type="search" />     </div> </form> {% endblock %}  {% block page_content %}  <div class="container">      {% if not cameras %}     {% if term != '' %}     <!-- No results alert -->     <div class="row">         <div id="no-results" class="col-xl-8 col-md-7 col-sm-8 col-8 mx-auto">             <div id="no-results-text" class="alert alert-info text-center my-auto" role="alert">No raptor cameras                 were                 found at the jobsite '{{ term }}'</div>         </div>     </div>     {% endif %}      {% else %}     <div class="results-container container-fluid d-flex flex-column">          <!-- Trigger all sirens button -->         <div class="row">             <div id="trigger-all" class="col-xl-6 col-md-5 col-sm-6 col-6 mx-auto">                 <form id="trigger-all-form" action="{% url 'camera_search:siren_search' %}" method="GET">                     <input type="hidden" name="current-url" value="{{ request.get_full_path }}">                     <button id="trigger-all-btn" name="pulse-all-sirens" type="submit"                         class="btn btn-lg btn-block btn-outline-danger btn-space js-trigger-all-sirens-btn"                         value="{{ cameras }}">Trigger                         all sirens at {{ term }}</button>                 </form>             </div>         </div>          <!-- Camera results table -->         <div class="row">             <div class="col-xl-8 col-md-7 col-sm-8 col-8 mx-auto">                 <table class="table table-responsive-sm table-hover table-borderless mx-auto">                      <thead>                         <tr class="header">                             <th scope="col" style="width:30%;">Site ID</th>                             <th scope="col" style="width:25%;">Job Site</th>                             <th scope="col" style="width:25%;">Asset Name</th>                             <th scope="col" style="width:20%;"></th>                         </tr>                     </thead>                      <tbody>                         {% for camera in cameras %}                         <tr>                             <!-- If site ID is available, bold it and put it in the siren button -->                             {% if camera.site_id != 'N/A' %}                             <td class="align-middle"><b>{{ camera.site_id }}</b></td>                             <td class="align-middle">{{ camera.site }}</td>                             <td class="align-middle">{{ camera.asset_name }}</td>                             <td class="align-middle">                                 <form id="{{ camera.asset_name }}-siren-form"                                     action="{% url 'camera_search:siren_search' %}" method="GET">                                     <input type="hidden" name="current-url" value="{{ request.get_full_path }}">                                     <button type="submit" name="pulse-siren" id="{{ camera.asset_name }}-siren-btn"                                         name="button-big-submit"                                         class="btn btn-outline-primary float-right js-single-trigger-btn" onclick=""                                         value="{{ camera.asset_name }}">{{ camera.site_id }}</button>                                 </form>                             </td>                              <!-- else, take bold off site ID ('N/A') and put the asset name in the siren button-->                             {% else %}                              <td class="align-middle">{{ camera.site_id }}</td>                             <td class="align-middle">{{ camera.site }}</td>                             <td class="align-middle">{{ camera.asset_name }}</td>                             <td class="align-middle">                                 <form id="{{ camera.asset_name }}-siren-form"                                     action="{% url 'camera_search:siren_search' %}" method="GET">                                     <input type="hidden" name="current-url" value="{{ request.get_full_path }}">                                     <button type="submit" name="pulse-siren" id="{{ camera.asset_name }}-siren-btn"                                         name="button-big-submit"                                         class="btn btn-outline-primary float-right js-single-trigger-btn" onclick=""                                         value="{{ camera.asset_name }}">{{ camera.asset_name }}</button>                                 </form>                             </td>                              {% endif %}                         </tr>                         {% endfor %}                     </tbody>                  </table>             </div>         </div> <!-- End entire table section -->      </div><!-- End {# else #} block-->     {% endif %}      <!-- Error messages -->     {% if messages %}     <ul class="messages">         {% for message in messages %}         <li{% if message.tags %} class="{{ message.tags }}" {% endif %}>{{ message }}</li>             {% endfor %}     </ul>     {% else %}     <!-- show success -->     {% endif %}  </div> <!-- End container holding everything below navbar -->  {% endblock %} {% block javascript %} <script type="text/javascript" src="{% static 'js/search.js' %}"></script> {% endblock %} 

/project/app/urls.py

from django.urls import path, re_path from . import views  app_name = 'camera_search'  urlpatterns = [     path('', views.siren_search, name = 'siren_search'), ] 

/project/urls.py

## This is the main urls.py file  from django.contrib import admin from django.urls import path, include from django.views.generic.base import RedirectView  urlpatterns = [     path('admin/', admin.site.urls),     path('siren-search/', include('camera_search.urls', namespace = 'camera_search')),     path('camera-info/', include('camera_info.urls', namespace="camera_info")),     path('', RedirectView.as_view(pattern_name = 'camera_search:siren_search', permanent=False)), ] 

Web app that can trigger sirens for personally owned cameras in remote locations

Web-app summary:

I’m a complete beginner in web development and I made a sample web application that can trigger sirens on security cameras located in remote locations. Here’s the functionality seen by the user:

  1. Go to website and brought to a landing page with a search bar.
  2. Type in the name of a location.
  3. Be shown all the cameras in that location, and next to each camera is a button to trigger its siren.
  4. There is also a button that triggers all the sirens in that location.

Searching for a location:

When the user searches for a location, the back-end routes this query to a function called search_by_jobsite(jobsite). This function establishes a connection with a third-party API and queries a mock database on Zoho.com. The results are processed and then returned to the server to be shown on the front-end.

Triggering a siren:

This is honestly extremely simple. When the button is pressed, the request on the back-end is routed to a function called pulse_siren(camera_name) that just makes a simple HTTP get request to a camera’s static IP address.

My thoughts:

After making this web-app I realized that Django was absolutely overkill since I don’t even have a local database. I’m essentially just using Django as a web-server and routing. Next time I should use something like Flask, but i’m interested in how I can improve my existing code. When making this project I was primarily focused on actually getting this thing up and running and then optimizing. I feel like my views.py file should be turned into most class-based-views (as they’re called in Django), and I read a lot up on this but I wasn’t exactly sure the best way to implement this.

I’m mostly concerned with cleaning up my views.py file and optimizing it for speed since it takes maybe a second to make the API call.


views.py

## views.py - this is where all the back-end processing happens for a user's request  ''' When making this project '''  from django.shortcuts import render, redirect from django.http import JsonResponse from django.core.exceptions import ObjectDoesNotExist from .models import CameraSystem, CameraModel, ControlByWeb, JobSite from django.core import serializers from django.conf import settings from django.contrib import messages from .pulse_siren import pulse_siren import json, ast, requests from zcrmsdk import ZCRMRecord, ZCRMRestClient, ZCRMModule, ZCRMException   def siren_search(request):      # Define the term in the search     term = request.GET.get('query', '').strip()     context = {'term': term}      # Handle the AJAX search     if 'query' in request.GET and request.is_ajax():         try:             cameras = CameraSystem.objects.filter(site__name__icontains=term)             json_response = serializers.serialize('json', cameras, fields=(                 'asset_name', 'site',), use_natural_foreign_keys=True, use_natural_primary_keys=True)             parsed = json.loads(json_response)             print(json.dumps(parsed, indent=4, sort_keys=True))          except ObjectDoesNotExist:             return JsonResponse({'success': False}, status=400)          return JsonResponse(json_response, safe=False, status=200)      # Handle when the user presses enter     elif 'query' in request.GET and term != '' and not request.is_ajax():          try:             # Get the list of cameras at the desired jobsite             deployed = search_by_jobsite(term)              # Sort the list so they show up in HTML as: PANTHER1, PANTHER2, PANTHER3, ..., etc.             context = {                 'cameras': sorted(deployed, key=lambda camera: camera['site_id']),                 'term': term             }          # Catch any error that the Zoho API might output         except ZCRMException as error:             print(error) # TODO             pass          return render(request, 'siren_search.html', context)      # Handle when the user presses a siren button for just one camera     elif 'pulse-siren' in request.GET:          # Get the current url so the we can show the same search results after they press the button         redirect_url = request.GET.get('current-url')         asset_name = request.GET.get('pulse-siren').upper()          # Pulse the siren on the desired camera, and for anything that happens add a message to the redirect         try:             response = pulse_siren(asset_name)             response.raise_for_status()             messages.add_message(request, messages.INFO, f"Successful for {asset_name}.")          except requests.exceptions.HTTPError as error:             if response.status_code == 401:                 errorString = f'Looks like {asset_name} is online, but the system was not able to log in.'                 messages.add_message(request, messages.INFO, errorString)             else:                 errorString = f'HTTP error for {asset_name}: {error}'                 messages.add_message(request, messages.INFO, errorString)             pass          except requests.exceptions.ConnectionError as error:             errorString = f'The system failed to connect for {asset_name}. Check to see if the unit is online. If it is, then then the system may have used a wrong username/password.'             messages.add_message(request, messages.INFO, errorString)             pass          except requests.exceptions.Timeout as error:             errorString = f'Timeout error for {asset_name}: the system tried to connect for three seconds but failed.'             messages.add_message(request, messages.INFO, errorString)             pass          except requests.exceptions.RequestException as error:             errorString = f'Oops, something weird happened for {asset_name}: {error}'             messages.add_message(request, messages.INFO, errorString)             pass          return redirect(redirect_url)      # Handle when the user wants to trigger all sirens     elif 'pulse-all-sirens' in request.GET:          # Get the cameras and the redirecut url         redirect_url = request.GET.get('current-url')         camera_json = request.GET.get('pulse-all-sirens')         camera_list = ast.literal_eval(camera_json) # for some reason json.loads() doesn't work, so use literal_eval ()          # Pulse the siren for each camera on the search results page         for camera in camera_list:             asset_name = camera['asset_name']              # Pulse the siren on the desired camera, and for anything that happens add a message to the redirect             try:                 response = pulse_siren(asset_name)                 response.raise_for_status()                 messages.add_message(request, messages.INFO, f"Successful for {asset_name}.")              except requests.exceptions.HTTPError as error:                 errorString = f'HTTP error for {asset_name}: {error}'                 messages.add_message(request, messages.INFO, errorString)                 pass              except requests.exceptions.ConnectionError as error:                 errorString = f'The system failed to connect for {asset_name}: Check to see if the unit is online, but the system may have used a wrong username/password.'                 messages.add_message(request, messages.INFO, errorString)                 pass              except requests.exceptions.Timeout as error:                 errorString = f'Timeout error for {asset_name}: The system tried to connect for three seconds but failed.'                 messages.add_message(request, messages.INFO, errorString)                 pass              except requests.exceptions.RequestException as error:                 errorString = f'Oops, something weird happened for {asset_name}: {error}'                 messages.add_message(request, messages.INFO, errorString)                 pass          return redirect(redirect_url)      else:         return render(request, 'siren_search.html', context)   def search_by_jobsite(jobsite):      # 'IP': camera['Static_IP'],      # Initialize the API client and search for cameras with a jobsite that matches the search     jobsite = jobsite.upper() # This must be in uppercase because the sites on ZOHO are all uppercase     config = settings.ZOHO_CONFIG     client = ZCRMRestClient.initialize(config)     all_cameras = ZCRMModule.get_instance('Vendors').search_records(f'{jobsite}')      # Iterate over each returned camera     deployed_cameras = []     for camera_record in all_cameras.data:          # Get some properties from the camera to filter results         camera = camera_record.field_data         status = camera['Status'].lower()         camera_type = camera['Type'].lower()         site = camera['Site']['name'].upper()          # Only get the cameras that are deployed at the jobsite of type 'raptor'         if site == jobsite and camera_type == 'raptor':              # Get properties if they exist             asset_name = camera.get('Vendor_Name', 'None')             site_id = camera.get('Multiple_Assets', 'None')              # If the properties exist, style them             if asset_name is not 'None':                 asset_name = asset_name.upper()             if site_id is not 'None':                 site_id = site_id.upper()              # Append this camera's dictionary to the list of deployed cameras             temp_dictionary = {'asset_name': asset_name, 'site_id': site_id, 'site': site.capitalize()}             deployed_cameras.append(temp_dictionary.copy())      return deployed_cameras   def pulse_siren(asset_name):      # Configure the url for the desired camera     camera_url = 'http://' + asset_name.lower() + settings.CAMERA_URL + settings.PULSE_SIREN_HALF_SECOND      # Pulse the siren on the camera for the preset time. I'm using 0.5 seconds right now so I don't annoy the office     username = settings.RAPTOR_AUTHENTICATION['username']     password = settings.RAPTOR_AUTHENTICATION['password']     pulseSiren = requests.get(camera_url, auth=(username, password), timeout = 3)     return pulseSiren  def get_camera_state(asset_name):      # Configure the url for the desired camera     camera_url = 'http://' + asset_name.lower() + settings.CAMERA_URL + 'state.xml'      # Connect to the camera's interface and grab its state     username = settings.RAPTOR_AUTHENTICATION['username']     password = settings.RAPTOR_AUTHENTICATION['password']     camera_state = requests.get(camera_url, auth=(username, password))     data = xmltodict.parse(connectByWebXMLState.text) 

siren_search.html

 <!-- siren_search.html --> {% extends "base.html" %} {% load static %}   {% block page_title %} Siren System {% endblock %}   {% block page_content %}  <!-- Search section --> <div class="container">     <div class="row">         <div id="search-title" class="col-xl-6 col-md-7 col-sm-8 col-8 mx-auto">             <h3>Siren system</h3>         </div>     </div>      <div class="row">         <div class="col-xl-6 col-md-7 col-sm-8 col-8 mx-auto">             <form id="searchform" action="{% url 'camera_search:siren_search' %}" method="GET">                 <div class="input-group">                     <input id="searchbar" name="query" autocomplete="on" onkeyup=getCameras(this.value) placeholder="Search for the name of a jobsite." class="form-control" type="search" />                 </div>             </form>         </div>     </div>      <!-- Show the trigger all button if there's cameras, or show no results -->     <div class="row">         <div id="trigger-all-and-no-results" class="col-xl-6 col-md-7 col-sm-8 col-8 mx-auto">              {% if cameras %}             <form id="trigger-all-form" action="{% url 'camera_search:siren_search' %}" method="GET">                 <input type="hidden" name="current-url" value="{{ request.get_full_path }}">                 <button id="trigger-all-btn" name="pulse-all-sirens" type="submit" class="btn btn-lg btn-block btn-outline-danger btn-space js-trigger-all-sirens-btn" value="{{ cameras }}">Trigger                     all sirens</button>             </form>              {% else %} {% if term != '' %}             <div id="no-results-text" class="alert alert-info text-center my-auto" role="alert">No cameras were found for {{ term }}</div>             {% endif %} {% endif %}          </div>     </div>      <!-- Show the cameras that were found in the search -->     {% if cameras %}     <div class="row">         <div class="col-xl-8 col-md-9 col-sm-10 col-10 mx-auto">             <table class="table table-responsive-sm table-hover table-borderless mx-auto">                   <thead>                     <tr class="header">                         <th scope="col" style="width:30%;">Site ID</th>                         <th scope="col" style="width:25%;">Job Site</th>                         <th scope="col" style="width:25%;">Asset Name</th>                         <th scope="col" style="width:20%;"></th>                     </tr>                 </thead>                  <tbody>                     {% for camera in cameras %}                     <tr>                         <td class="align-middle">{{ camera.site_id }}</td>                         <td class="align-middle">{{ camera.site }}</td>                         <td class="align-middle">{{ camera.asset_name }}</td>                         <td class="align-middle">                             <form id="{{ camera.asset_name }}-siren-form" action="{% url 'camera_search:siren_search' %}" method="GET">                                 <input type="hidden" name="current-url" value="{{ request.get_full_path }}">                                 <button type="submit" name="pulse-siren" id="{{ camera.asset_name }}-siren-btn" name="button-big-submit" class="btn btn-outline-primary float-right js-single-trigger-btn" onclick="" value="{{ camera.asset_name }}">{% if camera.site_id != 'None' %}{{ camera.site_id }}{% else %}{{ camera.asset_name }}{% endif %}</button>                             </form>                         </td>                     </tr>                     {% endfor %}                 </tbody>              </table>         </div>     </div>     {% endif %}   <!-- This is a WIP, this was just here so I can practice getting the messages from the server to the front-end --> {% if messages %}     <ul class="messages">         {% for message in messages %}         <li{% if message.tags %} class="{{ message.tags }}" {% endif %}>{{ message }}</li>             {% endfor %}     </ul>     {% else %}      <!-- show success -->      {% endif %} </div>  {% endblock %}  {% block javascript %} <script type="text/javascript" src="{% static 'js/search.js' %}"></script> {% endblock %}  

What the user sees:

Search results page