PYTHON · Code cell
# =====================================================================
# X9 | Code cell 03 | Lab 9 · ThingSpeak HTTPS upload
# Purpose: 3. Compare the controlled conditions
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import json, threading
from urllib.request import Request, urlopen
from urllib.parse import urlencode
# Define the reusable operation check; keep its logic separate from the trial.
def check(condition, message):
if not condition: raise RuntimeError(message)
# Actual HTTP requests, local teaching endpoint (not ThingSpeak cloud).
def http_trial():
"""Actual HTTP requests, local teaching endpoint (not ThingSpeak cloud)."""
from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer
from urllib.parse import parse_qs,urlsplit
rows=[]
class Handler(BaseHTTPRequestHandler):
def log_message(self,*a):pass
def send(self,status,data):
data=json.dumps(data).encode();self.send_response(status);self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(data)));self.end_headers();self.wfile.write(data)
def do_POST(self):
if self.path!='/update':return self.send(404,{})
try:
length=int(self.headers.get('Content-Length','0'));check(0<length<=4096,'size');p=parse_qs(self.rfile.read(length).decode());check(p['api_key']==['local-demo'],'key');t=float(p['field1'][0]);h=float(p['field2'][0]);check(-40<=t<=80 and 0<=h<=100,'range');rows.append({'field1':t,'field2':h,'entry_id':len(rows)+1});self.send(200,rows[-1]['entry_id'])
except (KeyError,ValueError,RuntimeError):self.send(400,{'error':'invalid sample'})
def do_GET(self):
if urlsplit(self.path).path!='/feeds.json':return self.send(404,{})
self.send(200,{'feeds':rows})
with ThreadingHTTPServer(('127.0.0.1',0),Handler) as s:
t=threading.Thread(target=s.serve_forever,daemon=True);t.start();base=f'http://127.0.0.1:{s.server_port}'
try:
for i in range(3):
req=Request(base+'/update',data=urlencode({'api_key':'local-demo','field1':24+i,'field2':60-i}).encode());check(json.load(urlopen(req,timeout=3))==i+1,'HTTP write ID mismatch')
from urllib.error import HTTPError
try:urlopen(Request(base+'/update',data=b'api_key=bad&field1=24&field2=60'),timeout=3)
except HTTPError as e:check(e.code==400,'unexpected error response')
else:raise RuntimeError('invalid key accepted')
observed=json.load(urlopen(base+'/feeds.json',timeout=3))['feeds'];check([x['field1'] for x in observed]==[24,25,26],'readback mismatch');return observed
finally:s.shutdown();t.join(3)
# One real HTTPS write/readback on a student's own private channel, only if opted in.
def thingspeak_live(channel,write_key,read_key=''):
"""One real HTTPS write/readback on a student's own private channel, only if opted in."""
import re
from urllib.error import HTTPError, URLError
channel=str(channel).strip();write_key=write_key.strip();read_key=read_key.strip()
check(channel.isdigit() and int(channel)>0,'Enter a positive numeric channel ID')
check(re.fullmatch(r'[A-Za-z0-9]{16}',write_key),'Enter the channel Write API Key, not the Read key or URL')
check(not read_key or re.fullmatch(r'[A-Za-z0-9]{16}',read_key),'Enter the private channel Read API Key or leave blank for a public channel')
req=Request('https://api.thingspeak.com/update.json',data=urlencode({'api_key':write_key,'field1':24.5,'field2':60,'status':'mock'}).encode(),method='POST',headers={'Content-Type':'application/x-www-form-urlencoded'})
try:
with urlopen(req,timeout=15) as response: r=json.load(response)
entry=r.get('entry_id') if isinstance(r,dict) else None
check(type(entry)==int and entry>0,'No positive entry ID; check the Write API Key, enabled fields and update interval (wait 20 seconds)')
check(str(r.get('channel_id'))==channel,'The write key belongs to a different channel than the requested readback ID')
req=Request(f'https://api.thingspeak.com/channels/{channel}/feeds/{entry}.json'+('?'+urlencode({'api_key':read_key}) if read_key else ''))
with urlopen(req,timeout=15) as response: observed=json.load(response)
check(float(observed['field1'])==24.5 and float(observed['field2'])==60,'Readback does not match the submitted data')
return {'entry_id':entry,'temperature':24.5,'humidity':60,'source':'mock'}
except HTTPError as e: raise RuntimeError(f'ThingSpeak HTTP {e.code}: verify key, channel permissions and pacing') from None
except (URLError,OSError,ValueError,KeyError,TypeError): raise RuntimeError('ThingSpeak request/readback failed; check network, fields and read permissions. Do not retry immediately.') from None