i used unittest + HTMLTestRunner to test the software,early it runs very well,but yestarday i found it occured an error
File "/usr/lib/python2.7/site-packages/cephmgmtclient/sds_cli_auto_test/HTMLTestRunner.py", line 558, in complete_output
return self.outputBuffer.getvalue()
AttributeError: '_TestResult' object has no attribute 'outputBuffer'
i searched the reason on internet,some people ask me to add the code in HTMLTestRunner.py and the code is below:
class _TestResult(TestResult):
# note: _TestResult is a pure representation of results.
# It lacks the output and reporting ability compares to unittest._TextTestResult.
def __init__(self, verbosity=1):
TestResult.__init__(self)
self.stdout0 = None
self.stderr0 = None
self.success_count = 0
self.failure_count = 0
self.error_count = 0
self.verbosity = verbosity
# result is a list of result in 4 tuple
# (
# result code (0: success; 1: fail; 2: error),
# TestCase object,
# Test output (byte string),
# stack trace,
# )
self.result = []
self.outputBuffer = io.BytesIO()
#self.test_start_time = round(time.time(), 2)
afer do this,it not occur the same error,but my test cases cannot run,when i python the case.py,the print is below
Begin to run test_template 1 and apply the job map
E setUpClass (__main__.Test_case01)
Time Elapsed: 0:00:00.013564
it is so strange!because it normal in last version and i never changed my test case!
i can not figure out
the all codes of HTMLTestRunner.py is below
# TODO: color stderr
# TODO: simplify javascript using ,ore than 1 class in the class attribute?
import datetime
import StringIO
import sys
import time
import unittest
from xml.sax import saxutils
# ------------------------------------------------------------------------
# The redirectors below are used to capture output during testing. Output
# sent to sys.stdout and sys.stderr are automatically captured. However
# in some cases sys.stdout is already cached before HTMLTestRunner is
# invoked (e.g. calling logging.basicConfig). In order to capture those
# output, use the redirectors for the cached stream.
#
# e.g.
# >>> logging.basicConfig(stream=HTMLTestRunner.stdout_redirector)
# >>>
class OutputRedirector(object):
""" Wrapper to redirect stdout or stderr """
def __init__(self, fp):
self.fp = fp
def write(self, s):
self.fp.write(s)
def writelines(self, lines):
self.fp.writelines(lines)
def flush(self):
self.fp.flush()
stdout_redirector = OutputRedirector(sys.stdout)
stderr_redirector = OutputRedirector(sys.stderr)
# ----------------------------------------------------------------------
# Template
class Template_mixin(object):
"""
Define a HTML template for report customerization and generation.
Overall structure of an HTML report
HTML
+------------------------+
|<html> |
| <head> |
| |
| STYLESHEET |
| +----------------+ |
| | | |
| +----------------+ |
| |
| </head> |
| |
| <body> |
| |
| HEADING |
| +----------------+ |
| | | |
| +----------------+ |
| |
| REPORT |
| +----------------+ |
| | | |
| +----------------+ |
| |
| ENDING |
| +----------------+ |
| | | |
| +----------------+ |
| |
| </body> |
|</html> |
+------------------------+
"""
STATUS = {
0: 'pass',
1: 'fail',
2: 'error',
}
DEFAULT_TITLE = 'Unit Test Report'
DEFAULT_DESCRIPTION = ''
# ------------------------------------------------------------------------
# HTML Template
HTML_TMPL = r"""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>%(title)s</title>
<meta name="generator" content="%(generator)s"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
%(stylesheet)s
</head>
<body>
<script language="javascript" type="text/javascript"><!--
output_list = Array();
/* level - 0:Summary; 1:Failed; 2:All */
function showCase(level) {
trs = document.getElementsByTagName("tr");
for (var i = 0; i < trs.length; i++) {
tr = trs[i];
id = tr.id;
if (id.substr(0,2) == 'ft') {
if (level < 1) {
tr.className = 'hiddenRow';
}
else {
tr.className = '';
}
}
if (id.substr(0,2) == 'pt') {
if (level > 1) {
tr.className = '';
}
else {
tr.className = 'hiddenRow';
}
}
}
}
function showClassDetail(cid, count) {
var id_list = Array(count);
var toHide = 1;
for (var i = 0; i < count; i++) {
tid0 = 't' + cid.substr(1) + '.' + (i+1);
tid = 'f' + tid0;
tr = document.getElementById(tid);
if (!tr) {
tid = 'p' + tid0;
tr = document.getElementById(tid);
}
id_list[i] = tid;
if (tr.className) {
toHide = 0;
}
}
for (var i = 0; i < count; i++) {
tid = id_list[i];
if (toHide) {
document.getElementById('div_'+tid).style.display = 'none'
document.getElementById(tid).className = 'hiddenRow';
}
else {
document.getElementById(tid).className = '';
}
}
}
function showTestDetail(div_id){
var details_div = document.getElementById(div_id)
var displayState = details_div.style.display
// alert(displayState)
if (displayState != 'block' ) {
displayState = 'block'
details_div.style.display = 'block'
}
else {
details_div.style.display = 'none'
}
}
function html_escape(s) {
s = s.replace(/&/g,'&');
s = s.replace(/</g,'<');
s = s.replace(/>/g,'>');
return s;
}
/* obsoleted by detail in <div>
function showOutput(id, name) {
var w = window.open("", //url
name,
"resizable,scrollbars,status,width=800,height=450");
d = w.document;
d.write("<pre>");
d.write(html_escape(output_list[id]));
d.write("\n");
d.write("<a href='javascript:window.close()'>close</a>\n");
d.write("</pre>\n");
d.close();
}
*/
--></script>
%(heading)s
%(report)s
%(ending)s
</body>
</html>
"""
# variables: (title, generator, stylesheet, heading, report, ending)
# ------------------------------------------------------------------------
# Stylesheet
#
# alternatively use a <link> for external style sheet, e.g.
# <link rel="stylesheet" href="$url" type="text/css">
STYLESHEET_TMPL = """
<style type="text/css" media="screen">
body { font-family: verdana, arial, helvetica, sans-serif; font-size: 80%; }
table { font-size: 100%; }
pre { }
/* -- heading ---------------------------------------------------------------------- */
h1 {
font-size: 16pt;
color: gray;
}
.heading {
margin-top: 0ex;
margin-bottom: 1ex;
}
.heading .attribute {
margin-top: 1ex;
margin-bottom: 0;
}
.heading .description {
margin-top: 2ex;
margin-bottom: 4ex;
}
/* -- css div popup ------------------------------------------------------------------------ */
a.popup_link {
}
a.popup_link:hover {
color: red;
}
.popup_window {
display: none;
position: relative;
left: 0px;
top: 0px;
/*border: solid #627173 1px; */
padding: 10px;
background-color: #E6E6D6;
font-family: "Lucida Console", "Courier New", Courier, monospace;
text-align: left;
font-size: 8pt;
width: 500px;
}
}
/* -- report ------------------------------------------------------------------------ */
#show_detail_line {
margin-top: 3ex;
margin-bottom: 1ex;
}
#result_table {
width: 80%;
border-collapse: collapse;
border: 1px solid #777;
}
#header_row {
font-weight: bold;
color: white;
background-color: #777;
}
#result_table td {
border: 1px solid #777;
padding: 2px;
}
#total_row { font-weight: bold; }
.passClass { background-color: #6c6; }
.failClass { background-color: #c60; }
.errorClass { background-color: #c00; }
.passCase { color: #6c6; }
.failCase { color: #c60; font-weight: bold; }
.errorCase { color: #c00; font-weight: bold; }
.hiddenRow { display: none; }
.testcase { margin-left: 2em; }
/* -- ending ---------------------------------------------------------------------- */
#ending {
}
</style>
"""
# ------------------------------------------------------------------------
# Heading
#
HEADING_TMPL = """<div class='heading'>
<h1>%(title)s</h1>
%(parameters)s
<p class='description'>%(description)s</p>
</div>
""" # variables: (title, parameters, description)
HEADING_ATTRIBUTE_TMPL = """<p class='attribute'><strong>%(name)s:</strong> %(value)s</p>
""" # variables: (name, value)
# ------------------------------------------------------------------------
# Report
#
REPORT_TMPL = """
<p id='show_detail_line'>Show
<a href='javascript:showCase(0)'>Summary</a>
<a href='javascript:showCase(1)'>Failed</a>
<a href='javascript:showCase(2)'>All</a>
</p>
<table id='result_table'>
<colgroup>
<col align='left' />
<col align='right' />
<col align='right' />
<col align='right' />
<col align='right' />
<col align='right' />
</colgroup>
<tr id='header_row'>
<td>Test Group/Test case</td>
<td>Count</td>
<td>Pass</td>
<td>Fail</td>
<td>Error</td>
<td>View</td>
</tr>
%(test_list)s
<tr id='total_row'>
<td>Total</td>
<td>%(count)s</td>
<td>%(Pass)s</td>
<td>%(fail)s</td>
<td>%(error)s</td>
<td> </td>
</tr>
</table>
""" # variables: (test_list, count, Pass, fail, error)
REPORT_CLASS_TMPL = r"""
<tr class='%(style)s'>
<td>%(desc)s</td>
<td>%(count)s</td>
<td>%(Pass)s</td>
<td>%(fail)s</td>
<td>%(error)s</td>
<td>Detail</td>
</tr>
""" # variables: (style, desc, count, Pass, fail, error, cid)
REPORT_TEST_WITH_OUTPUT_TMPL = r"""
<tr id='%(tid)s' class='%(Class)s'>
<td class='%(style)s'><div class='testcase'>%(desc)s</div></td>
<td colspan='5' align='center'>
<!--css div popup start-->
<a class="popup_link" onfocus='this.blur();' href="javascript:showTestDetail('div_%(tid)s')" >
%(status)s</a>
<div id='div_%(tid)s' class="popup_window">
<div style='text-align: right; color:red;cursor:pointer'>
<a onfocus='this.blur();' onclick="document.getElementById('div_%(tid)s').style.display = 'none' " >
[x]</a>
</div>
<pre>
%(script)s
</pre>
</div>
<!--css div popup end-->
</td>
</tr>
""" # variables: (tid, Class, style, desc, status)
REPORT_TEST_NO_OUTPUT_TMPL = r"""
<tr id='%(tid)s' class='%(Class)s'>
<td class='%(style)s'><div class='testcase'>%(desc)s</div></td>
<td colspan='5' align='center'>%(status)s</td>
</tr>
""" # variables: (tid, Class, style, desc, status)
REPORT_TEST_OUTPUT_TMPL = r"""
%(id)s: %(output)s
""" # variables: (id, output)
# ------------------------------------------------------------------------
# ENDING
#
ENDING_TMPL = """<div id='ending'> </div>"""
# -------------------- The end of the Template class -------------------
TestResult = unittest.TestResult
class _TestResult(TestResult):
# note: _TestResult is a pure representation of results.
# It lacks the output and reporting ability compares to unittest._TextTestResult.
def __init__(self, verbosity=1):
TestResult.__init__(self)
self.stdout0 = None
self.stderr0 = None
self.success_count = 0
self.failure_count = 0
self.error_count = 0
self.verbosity = verbosity
# result is a list of result in 4 tuple
# (
# result code (0: success; 1: fail; 2: error),
# TestCase object,
# Test output (byte string),
# stack trace,
# )
self.result = []
def startTest(self, test):
TestResult.startTest(self, test)
# just one buffer for both stdout and stderr
self.outputBuffer = StringIO.StringIO()
stdout_redirector.fp = self.outputBuffer
stderr_redirector.fp = self.outputBuffer
self.stdout0 = sys.stdout
self.stderr0 = sys.stderr
sys.stdout = stdout_redirector
sys.stderr = stderr_redirector
def complete_output(self):
"""
Disconnect output redirection and return buffer.
Safe to call multiple times.
"""
if self.stdout0:
sys.stdout = self.stdout0
sys.stderr = self.stderr0
self.stdout0 = None
self.stderr0 = None
return self.outputBuffer.getvalue()
def stopTest(self, test):
# Usually one of addSuccess, addError or addFailure would have been called.
# But there are some path in unittest that would bypass this.
# We must disconnect stdout in stopTest(), which is guaranteed to be called.
self.complete_output()
def addSuccess(self, test):
self.success_count += 1
TestResult.addSuccess(self, test)
output = self.complete_output()
self.result.append((0, test, output, ''))
if self.verbosity > 1:
sys.stderr.write('ok ')
sys.stderr.write(str(test))
sys.stderr.write('\n')
else:
sys.stderr.write('.')
def addError(self, test, err):
self.error_count += 1
TestResult.addError(self, test, err)
_, _exc_str = self.errors[-1]
output = self.complete_output()
self.result.append((2, test, output, _exc_str))
if self.verbosity > 1:
sys.stderr.write('E ')
sys.stderr.write(str(test))
sys.stderr.write('\n')
else:
sys.stderr.write('E')
def addFailure(self, test, err):
self.failure_count += 1
TestResult.addFailure(self, test, err)
_, _exc_str = self.failures[-1]
output = self.complete_output()
self.result.append((1, test, output, _exc_str))
if self.verbosity > 1:
sys.stderr.write('F ')
sys.stderr.write(str(test))
sys.stderr.write('\n')
else:
sys.stderr.write('F')
class HTMLTestRunner(Template_mixin):
"""
"""
def __init__(self, stream=sys.stdout, verbosity=1, title=None, description=None):
self.stream = stream
self.verbosity = verbosity
if title is None:
self.title = self.DEFAULT_TITLE
else:
self.title = title
if description is None:
self.description = self.DEFAULT_DESCRIPTION
else:
self.description = description
self.startTime = datetime.datetime.now()
def run(self, test):
"Run the given test case or test suite."
result = _TestResult(self.verbosity)
test(result)
self.stopTime = datetime.datetime.now()
self.generateReport(test, result)
print >>sys.stderr, '\nTime Elapsed: %s' % (self.stopTime-self.startTime)
return result
def sortResult(self, result_list):
# unittest does not seems to run in any particular order.
# Here at least we want to group them together by class.
rmap = {}
classes = []
for n,t,o,e in result_list:
cls = t.__class__
if not rmap.has_key(cls):
rmap[cls] = []
classes.append(cls)
rmap[cls].append((n,t,o,e))
r = [(cls, rmap[cls]) for cls in classes]
return r
def getReportAttributes(self, result):
"""
Return report attributes as a list of (name, value).
Override this to add custom attributes.
"""
startTime = str(self.startTime)[:19]
duration = str(self.stopTime - self.startTime)
status = []
if result.success_count: status.append('Pass %s' % result.success_count)
if result.failure_count: status.append('Failure %s' % result.failure_count)
if result.error_count: status.append('Error %s' % result.error_count )
if status:
status = ' '.join(status)
else:
status = 'none'
return [
('Start Time', startTime),
('Duration', duration),
('Status', status),
]
def generateReport(self, test, result):
report_attrs = self.getReportAttributes(result)
generator = 'HTMLTestRunner %s' % __version__
stylesheet = self._generate_stylesheet()
heading = self._generate_heading(report_attrs)
report = self._generate_report(result)
ending = self._generate_ending()
output = self.HTML_TMPL % dict(
title = saxutils.escape(self.title),
generator = generator,
stylesheet = stylesheet,
heading = heading,
report = report,
ending = ending,
)
self.stream.write(output.encode('utf8'))
def _generate_stylesheet(self):
return self.STYLESHEET_TMPL
def _generate_heading(self, report_attrs):
a_lines = []
for name, value in report_attrs:
line = self.HEADING_ATTRIBUTE_TMPL % dict(
name = saxutils.escape(name),
value = saxutils.escape(value),
)
a_lines.append(line)
heading = self.HEADING_TMPL % dict(
title = saxutils.escape(self.title),
parameters = ''.join(a_lines),
description = saxutils.escape(self.description),
)
return heading
def _generate_report(self, result):
rows = []
sortedResult = self.sortResult(result.result)
for cid, (cls, cls_results) in enumerate(sortedResult):
# subtotal for a class
np = nf = ne = 0
for n,t,o,e in cls_results:
if n == 0: np += 1
elif n == 1: nf += 1
else: ne += 1
# format class description
if cls.__module__ == "__main__":
name = cls.__name__
else:
name = "%s.%s" % (cls.__module__, cls.__name__)
doc = cls.__doc__ and cls.__doc__.split("\n")[0] or ""
desc = doc and '%s: %s' % (name, doc) or name
row = self.REPORT_CLASS_TMPL % dict(
style = ne > 0 and 'errorClass' or nf > 0 and 'failClass' or 'passClass',
desc = desc,
count = np+nf+ne,
Pass = np,
fail = nf,
error = ne,
cid = 'c%s' % (cid+1),
)
rows.append(row)
for tid, (n,t,o,e) in enumerate(cls_results):
self._generate_report_test(rows, cid, tid, n, t, o, e)
report = self.REPORT_TMPL % dict(
test_list = ''.join(rows),
count = str(result.success_count+result.failure_count+result.error_count),
Pass = str(result.success_count),
fail = str(result.failure_count),
error = str(result.error_count),
)
return report
def _generate_report_test(self, rows, cid, tid, n, t, o, e):
# e.g. 'pt1.1', 'ft1.1', etc
has_output = bool(o or e)
tid = (n == 0 and 'p' or 'f') + 't%s.%s' % (cid+1,tid+1)
name = t.id().split('.')[-1]
doc = t.shortDescription() or ""
desc = doc and ('%s: %s' % (name, doc)) or name
tmpl = has_output and self.REPORT_TEST_WITH_OUTPUT_TMPL or self.REPORT_TEST_NO_OUTPUT_TMPL
# o and e should be byte string because they are collected from stdout and stderr?
if isinstance(o,str):
# TODO: some problem with 'string_escape': it escape \n and mess up formating
# uo = unicode(o.encode('string_escape'))
uo = o.decode('latin-1')
else:
uo = o
if isinstance(e,str):
# TODO: some problem with 'string_escape': it escape \n and mess up formating
# ue = unicode(e.encode('string_escape'))
ue = e.decode('latin-1')
else:
ue = e
script = self.REPORT_TEST_OUTPUT_TMPL % dict(
id = tid,
output = saxutils.escape(uo+ue),
)
row = tmpl % dict(
tid = tid,
Class = (n == 0 and 'hiddenRow' or 'none'),
style = n == 2 and 'errorCase' or (n == 1 and 'failCase' or 'none'),
desc = desc,
script = script,
status = self.STATUS[n],
)
rows.append(row)
if not has_output:
return
def _generate_ending(self):
return self.ENDING_TMPL
##############################################################################
# Facilities for running tests from the command line
##############################################################################
# Note: Reuse unittest.TestProgram to launch test. In the future we may
# build our own launcher to support more specific command line
# parameters like test title, CSS, etc.
class TestProgram(unittest.TestProgram):
"""
A variation of the unittest.TestProgram. Please refer to the base
class for command line parameters.
"""
def runTests(self):
# Pick HTMLTestRunner as the default test runner.
# base class's testRunner parameter is not useful because it means
# we have to instantiate HTMLTestRunner before we know self.verbosity.
if self.testRunner is None:
self.testRunner = HTMLTestRunner(verbosity=self.verbosity)
unittest.TestProgram.runTests(self)
main = TestProgram
##############################################################################
# Executing this module from the command line
##############################################################################
if __name__ == "__main__":
main(module=None)
at last i add a line in _TestResult() function,and the code is below
class _TestResult(TestResult):
# note: _TestResult is a pure representation of results.
# It lacks the output and reporting ability compares to unittest._TextTestResult.
def __init__(self, verbosity=1):
TestResult.__init__(self)
self.stdout0 = None
self.stderr0 = None
self.success_count = 0
self.failure_count = 0
self.error_count = 0
self.verbosity = verbosity
# result is a list of result in 4 tuple
# (
# result code (0: success; 1: fail; 2: error),
# TestCase object,
# Test output (byte string),
# stack trace,
# )
self.result = []
self.outputBuffer = StringIO.StringIO() #this the added code!!!
and my program occur error because another place the code is wrong ,i fixed it !
so it works add the code!
Related
File: index.html
<html>
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- jquery -->
<script src="jquery-3.5.1.min.js"></script>
<!-- own javascript -->
<script src="telephone_calls.js"></script>
</head>
<body>
<audio style="width:100%;margin-top:5mm;background:rgb(241,243,244)" id="audio" autoplay="true" controls="true"></audio>
</body>
</html>
File telephone_calls.js
// peer connection
var pc = null;
function createPeerConnection() {
var config = {
sdpSemantics: 'unified-plan',
iceServers: [{urls: ['stun:stun.l.google.com:19302']}]
};
pc = new RTCPeerConnection(config);
// connect audio
pc.addEventListener('track', function(evt) {
if (evt.track.kind == 'audio'){
document.getElementById('audio').srcObject = evt.streams[0];
};
});
return pc;
}
function negotiate() {
return pc.createOffer().then(function(offer) {
return pc.setLocalDescription(offer);
}).then(function() {
// wait for ICE gathering to complete
return new Promise(function(resolve) {
console.log(pc.iceGatheringState);
if (pc.iceGatheringState === 'complete') {
resolve();
} else {
function checkState() {
console.log(pc.iceGatheringState);
if (pc.iceGatheringState === 'complete') {
pc.removeEventListener('icegatheringstatechange', checkState);
resolve();
}
}
pc.addEventListener('icegatheringstatechange', checkState);
}
});
}).then(function() {
var offer = pc.localDescription;
return fetch('/offer', {
body: JSON.stringify({
sdp: offer.sdp,
type: offer.type
}),
headers: {
'Content-Type': 'application/json'
},
method: 'POST'
});
}).then(function(response) {
return response.json();
}).then(function(answer) {
return pc.setRemoteDescription(answer);
}).catch(function(e) {
alert(e);
console.log(e);
});
}
function start() {
pc = createPeerConnection();
dc = pc.createDataChannel('radio_metadata', {"ordered": true});
dc.onclose = function() {
};
dc.onopen = function() {
};
dc.onmessage = function(evt) {
console.log(evt.data);
};
//negotiate();
constraints = {audio:true,video:false};
navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
stream.getTracks().forEach(function(track) {
pc.addTrack(track, stream);
});
return negotiate();
}, function(err) {
alert('Could not acquire media: ' + err);
});
}
$(document).ready(function(){
start();
})
File: server.py
from aiohttp import web
from aiortc.mediastreams import MediaStreamTrack
from aiortc import RTCPeerConnection, RTCSessionDescription
from aiortc.contrib.media import MediaPlayer
from pydub import AudioSegment
import av
import pyaudio
import asyncio
import json
import os
from multiprocessing import Process, freeze_support
from queue import Queue
import sys
import threading
from time import sleep
import fractions
import time
class RadioServer(Process):
def __init__(self,q):
super().__init__()
self.q = q
self.ROOT = os.path.dirname(__file__)
self.pcs = []
self.channels = []
self.stream_offers = []
def run(self):
self.app = web.Application()
self.app.on_shutdown.append(self.on_shutdown)
self.app.router.add_get("/", self.index)
self.app.router.add_get("/telephone_calls.js", self.javascript)
self.app.router.add_get("/jquery-3.5.1.min.js", self.jquery)
self.app.router.add_post("/offer", self.offer)
threading.Thread(target=self.fill_the_queues).start()
web.run_app(self.app, access_log=None, host="192.168.1.20", port="8080", ssl_context=None)
def fill_the_queues(self):
while(True):
frame = self.q.get()
for stream_offer in self.stream_offers:
stream_offer.q.put(frame)
async def index(self,request):
content = open(os.path.join(self.ROOT, "index.html"), encoding="utf8").read()
return web.Response(content_type="text/html", text=content)
async def javascript(self,request):
content = open(os.path.join(self.ROOT, "telephone_calls.js"), encoding="utf8").read()
return web.Response(content_type="application/javascript", text=content)
async def jquery(self,request):
content = open(os.path.join(self.ROOT, "jquery-3.5.1.min.js"), encoding="utf8").read()
return web.Response(content_type="application/javascript", text=content)
async def offer(self,request):
params = await request.json()
offer = RTCSessionDescription(sdp=params["sdp"], type=params["type"])
pc = RTCPeerConnection()
self.pcs.append(pc)
# prepare epalxeis media
self.stream_offers.append(CustomRadioStream())
pc.addTrack(self.stream_offers[-1])
#player = MediaPlayer(os.path.join(self.ROOT, "ΑΓΙΑ ΚΥΡΙΑΚΗ.mp3"))
#pc.addTrack(player.audio)
#pc.on("datachannel")
def on_datachannel(channel):
self.channels.append(channel)
self.send_channel_message(str(len(self.pcs)))
#pc.on("iceconnectionstatechange")
async def on_iceconnectionstatechange():
if pc.iceConnectionState == "failed":
self.pcs.remove(pc)
print("Current peer connections:"+str(len(self.pcs)))
# handle offer
await pc.setRemoteDescription(offer)
# send answer
answer = await pc.createAnswer()
await pc.setLocalDescription(answer)
return web.Response(content_type="application/json",text=json.dumps({"sdp": pc.localDescription.sdp, "type": pc.localDescription.type}))
async def on_shutdown(self,app):
# close peer connections
if self.pcs:
coros = [pc.close() for pc in self.pcs]
await asyncio.gather(*coros)
self.pcs = []
self.channels = []
self.stream_offers = []
def send_channel_message(self,message):
for channel in self.channels:
channel.send(message)
class CustomRadioStream(MediaStreamTrack):
kind = "audio"
def __init__(self):
super().__init__() # don't forget this!
self.q = Queue()
self._start = None
async def recv(self):
frame = self.q.get()
frame_time = frame.time
if self._start is None:
self._start = time.time() - frame_time
else:
wait = self._start + frame_time - time.time()
await asyncio.sleep(wait)
return frame
class RadioOutputStream:
def __init__(self,q):
self.sample_rate = 44800
self.AUDIO_PTIME = 0.744
self.samples = int(self.AUDIO_PTIME * self.sample_rate)
self.packet_time = 20
self.FORMAT = pyaudio.paInt16
self.CHANNELS = 2
self.RATE = self.sample_rate
self.CHUNK = int(44100*0.744)
self.file_segment = AudioSegment.from_file(r"ΑΓΙΑ ΚΥΡΙΑΚΗ.mp3").set_frame_rate(self.sample_rate)
self.duration_milliseconds = len(self.file_segment)
self.chunk_number = 0
self.silence = AudioSegment.silent(duration=self.packet_time)
self.q = q
self.codec = av.CodecContext.create('pcm_s16le', 'r')
self.codec.sample_rate = 44800
self.codec.channels = 2
self.audio_samples = 0
def run_stream(self):
while(True):
time_start = time.time()
if((self.chunk_number+1)*(self.packet_time)<=self.duration_milliseconds):
final_slice = self.file_segment[self.chunk_number*self.packet_time:(self.chunk_number+1)*self.packet_time]
#final_slice = final_slice + 100
self.chunk_number += 1
packet = av.Packet(final_slice.raw_data)
frame = self.codec.decode(packet)[0]
frame.pts = self.audio_samples
frame.time_base = fractions.Fraction(1, self.codec.sample_rate)
self.audio_samples += frame.samples
self.q.put(frame)
else:
if(self.chunk_number*self.packet_time<self.duration_milliseconds):
final_slice = self.file_segment[self.chunk_number*self.packet_time:]
final_slice = final_slice + self.silence
#final_slice = final_slice + 100
self.chunk_number += 1
packet = av.Packet(final_slice.raw_data)
frame = self.codec.decode(packet)[0]
frame.pts = self.audio_samples
frame.time_base = fractions.Fraction(1, self.codec.sample_rate)
self.audio_samples += frame.samples
self.q.put(frame)
else:
#start song from begin
self.chunk_number=0
#time_end = time.time()
#sleep_time = time_end-time_start
#if sleep_time>0.020:
# sleep(sleep_time-0.020)
sleep(0.01)
if __name__ == "__main__":
freeze_support()
q = Queue()
radio_stream = RadioOutputStream(q)
threading.Thread(target=radio_stream.run_stream).start()
custom_server_child_process = RadioServer(q)
custom_server_child_process.run()
I want to change this:
constraints = {audio:true,video:false};
navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
stream.getTracks().forEach(function(track) {
pc.addTrack(track, stream);
});
return negotiate();
}, function(err) {
alert('Could not acquire media: ' + err);
});
to this:
negotiate();
but if i do that the following error is oquered in the server side:
C:\Users\Χρήστος\Desktop\radio>python server.py
======== Running on http://192.168.1.20:8080 ========
(Press CTRL+C to quit)
Error handling request
Traceback (most recent call last):
File "C:\Python\lib\site-packages\aiohttp\web_protocol.py", line 422, in _handle_request
resp = await self._request_handler(request)
File "C:\Python\lib\site-packages\aiohttp\web_app.py", line 499, in _handle
resp = await handler(request)
File "C:\Users\Χρήστος\Desktop\radio\server.py", line 90, in offer
await pc.setLocalDescription(answer)
File "C:\Python\lib\site-packages\aiortc\rtcpeerconnection.py", line 768, in setLocalDescription
t._currentDirection = and_direction(t.direction, t._offerDirection)
File "C:\Python\lib\site-packages\aiortc\rtcpeerconnection.py", line 247, in and_direction
return sdp.DIRECTIONS[sdp.DIRECTIONS.index(a) & sdp.DIRECTIONS.index(b)]
ValueError: None is not in list
Can anyone help me to create an empty offer please?
I change the negotiate javascript function.
Now is:
function negotiate() {
return pc.createOffer({offerToReceiveAudio:true}).then(function(offer) {
return pc.setLocalDescription(offer);
}).then(function() {
// wait for ICE gathering to complete
return new Promise(function(resolve) {
console.log(pc.iceGatheringState);
if (pc.iceGatheringState === 'complete') {
resolve();
} else {
function checkState() {
console.log(pc.iceGatheringState);
if (pc.iceGatheringState === 'complete') {
pc.removeEventListener('icegatheringstatechange', checkState);
resolve();
}
}
pc.addEventListener('icegatheringstatechange', checkState);
}
});
}).then(function() {
var offer = pc.localDescription;
return fetch('/offer', {
body: JSON.stringify({
sdp: offer.sdp,
type: offer.type
}),
headers: {
'Content-Type': 'application/json'
},
method: 'POST'
});
}).then(function(response) {
return response.json();
}).then(function(answer) {
return pc.setRemoteDescription(answer);
}).catch(function(e) {
alert(e);
console.log(e);
});
}
The only change is:
pc.createOffer()
-->
pc.createOffer({offerToReceiveAudio:true})
Link for further research
I am creating a simulated covid-care center in which i am using python's flask, html etc.
In this i will have a table showing some values at the home screen and then a chatbot and faq page. I have made the chat bot and faqs but i am having troubles updating my html data dynamically. (The data is created at the backend using random and thread modules).
Here is my main.py:
import flask
import time
import mysql.connector
app = flask.Flask(__name__)
app.static_folder = 'static'
#I am storing the values in a database
f = mysql.connector.connect(host = "localhost", user = "root", passwd = "")
mycur = f.cursor()
mycur.execute("use one_stop_healthcare;")
mycur.execute("select * from ccinfo;")
lines = mycur.fetchall()
#app.route("/")
def print_val():
global lines
return flask.render_template("index.html", lines = lines)
app.run()
Here is my index.html which is stored in a templates directory:
<html>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
text-align: center;
}
.button {
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
.button1 {background-color: #4CAF50;} /* Green */
.button2 {background-color: #008CBA;} /* Blue */
</style>
<head>
<title> One Stop Healthcare </title>
</head>
<body>
<h2> The data for all the COVID care centers </h1>
<table style="width:100%">
<tr>
<th> ID </th>
<th> NAME </th>
<th> LOCATION </th>
<th> BEDS </th>
<th> DISCARGED </th>
<th> ACTIVE </th>
<th> DEAD </th>
<th> DOCTORS </th>
<th> MONEY </th>
<th> PPE_KITS </th>
<th> BLANKETS </th>
<th> MASKS </th>
<th> SANITIZER </th>
</tr>
{% for line in lines %}
<tr>
{% for i in line %}
<td>{{ i }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<button type="button"> Chatbot </button>
<button type="button"> FAQs </button>
</body>
</html>
Here is my database + inserting the values into the database (You just need to run this once to insert the values and create the database). It doesn't have a issue
import mysql.connector
f = mysql.connector.connect(host = "localhost", user = "root", passwd = "")
mycur = f.cursor()
mycur.execute("create database One_Stop_Healthcare;")
f.commit()
mycur.execute("use One_Stop_Healthcare;")
print("database created")
que = "create table ccinfo(ID INTEGER NOT NULL primary key, NAME varchar(20), LOCATION varchar(20), BEDS integer, DISCHARGED integer, ACTIVE integer, DEAD integer, DOCTORS integer, MONEY integer, PPE_KITS integer, BLANKETS integer, MASKS integer, SANITIZER integer);"
mycur.execute(que)
print("table created")
mycur.execute("insert into ccinfo(ID, NAME, LOCATION, BEDS, DISCHARGED, ACTIVE, DEAD, DOCTORS, MONEY , PPE_KITS, BLANKETS, MASKS, SANITIZER)values(1, 'Ward-1', 'KRM', 500, 100, 300, 50, 25, 100000, 20, 100, 100, 70);")
mycur.execute("insert into ccinfo(ID, NAME, LOCATION, BEDS, DISCHARGED, ACTIVE, DEAD, DOCTORS, MONEY , PPE_KITS, BLANKETS, MASKS, SANITIZER)values(2, 'Ward-2', 'KRM', 1000, 290, 700, 150, 78, 250000, 40, 600, 300, 130);")
mycur.execute("insert into ccinfo(ID, NAME, LOCATION, BEDS, DISCHARGED, ACTIVE, DEAD, DOCTORS, MONEY , PPE_KITS, BLANKETS, MASKS, SANITIZER)values(3, 'Ward-3', 'KRM', 50, 10, 30, 5, 5, 80000, 7, 50, 30, 40);")
mycur.execute("insert into ccinfo(ID, NAME, LOCATION, BEDS, DISCHARGED, ACTIVE, DEAD, DOCTORS, MONEY , PPE_KITS, BLANKETS, MASKS, SANITIZER)values(4, 'Ward-4', 'HSR', 1500, 400, 1300, 250, 100, 400000, 70, 500, 300, 150);")
mycur.execute("insert into ccinfo(ID, NAME, LOCATION, BEDS, DISCHARGED, ACTIVE, DEAD, DOCTORS, MONEY , PPE_KITS, BLANKETS, MASKS, SANITIZER)values(5, 'Ward-5', 'Bellandur', 500, 50, 100, 25, 40, 90000, 30, 100, 90, 90);")
f.commit()
And finally here is where i am simulating the data
import threading
import time
import random
import mysql.connector
TC=5 #Total thread count
count = 0
thr = [0 for i in range(TC)]
db_data = [[] for i in range(TC+1)]
def print_time():
global count
global db_data
count = count + 1
mylocal = count
'''
1: id
2: location
3: beds
4: discharged
5: active
6: dead
7: doctors
8: money
9: ppe kits
10: blankets
11: masks
12: sanitizer
'''
i = 0
while i < 5:
i = i+1
x = random.randint(1,350)
#print(x)
if x == 1:
db_data[mylocal][3] = db_data[mylocal][3] + 50
st = "UPDATE ccinfo SET BEDS = {} where ID = {}".format(db_data[mylocal][3], mylocal)
elif x == 2 and db_data[mylocal][3] > 50:
db_data[mylocal][3] = db_data[mylocal][3] - 50
st = "UPDATE ccinfo SET BEDS = {} where ID = {}".format(db_data[mylocal][3], mylocal)
elif x == 3:
db_data[mylocal][7] = db_data[mylocal][7] + 1
st = "UPDATE ccinfo SET DOCTORS = {} where ID = {}".format(db_data[mylocal][7], mylocal)
elif x == 4 and db_data[mylocal][7] > 7:
db_data[mylocal][7] = db_data[mylocal][7] - 1
st = "UPDATE ccinfo SET DOCTORS = {} where ID = {}".format(db_data[mylocal][7], mylocal)
elif x > 4 and x < 101:
db_data[mylocal][4] = db_data[mylocal][4] + 1
st = "UPDATE ccinfo SET DISCHARGED = {} where ID = {}".format(db_data[mylocal][4], mylocal)
elif x > 100 and x < 201:
db_data[mylocal][5] = db_data[mylocal][5] + 1
st = "UPDATE ccinfo SET ACTIVE = {} where ID = {}".format(db_data[mylocal][5], mylocal)
elif x > 200 and x < 211:
db_data[mylocal][6] = db_data[mylocal][6] + 1
st = "UPDATE ccinfo SET DEAD = {} where ID = {}".format(db_data[mylocal][6], mylocal)
elif x > 210 and x < 221:
db_data[mylocal][8] = db_data[mylocal][8] + 10000
st = "UPDATE ccinfo SET MONEY = {} where ID = {}".format(db_data[mylocal][8], mylocal)
elif x > 220 and x < 231 and db_data[mylocal][8] > 20000:
db_data[mylocal][8] = db_data[mylocal][8] - 10000
st = "UPDATE ccinfo SET MONEY = {} where ID = {}".format(db_data[mylocal][8], mylocal)
elif x > 230 and x < 241:
db_data[mylocal][9] = db_data[mylocal][9] + 5
st = "UPDATE ccinfo SET PPE_KITS = {} where ID = {}".format(db_data[mylocal][9], mylocal)
elif x > 240 and x < 251 and db_data[mylocal][9] > 0:
db_data[mylocal][9] = db_data[mylocal][9] - 5
st = "UPDATE ccinfo SET PPE_KITS = {} where ID = {}".format(db_data[mylocal][9], mylocal)
elif x > 250 and x < 261:
db_data[mylocal][10] = db_data[mylocal][10] + 5
st = "UPDATE ccinfo SET BLANKETS = {} where ID = {}".format(db_data[mylocal][10], mylocal)
elif x > 260 and x < 271 and db_data[mylocal][10] > 0:
db_data[mylocal][10] = db_data[mylocal][10] - 5
st = "UPDATE ccinfo SET BLANKETS = {} where ID = {}".format(db_data[mylocal][10], mylocal)
elif x > 270 and x < 281:
db_data[mylocal][11] = db_data[mylocal][11] + 5
st = "UPDATE ccinfo SET MASKS = {} where ID = {}".format(db_data[mylocal][11], mylocal)
elif x > 280 and x < 291 and db_data[mylocal][11] > 0:
db_data[mylocal][11] = db_data[mylocal][11] - 5
st = "UPDATE ccinfo SET MASKS = {} where ID = {}".format(db_data[mylocal][11], mylocal)
elif x > 290 and x < 301:
db_data[mylocal][12] = db_data[mylocal][12] + 5
st = "UPDATE ccinfo SET SANITIZER = {} where ID = {}".format(db_data[mylocal][12], mylocal)
elif x > 300 and x < 311 and db_data[mylocal][12] > 0:
db_data[mylocal][12] = db_data[mylocal][12] - 5
st = "UPDATE ccinfo SET SANITIZER = {} where ID = {}".format(db_data[mylocal][12], mylocal)
print(st)
mycur.execute(st)
f.commit()
time.sleep(10)
if __name__ == "__main__":
f = mysql.connector.connect(host = "localhost", user = "root", passwd = "")
mycur = f.cursor()
mycur.execute("use one_stop_healthcare;")
mycur.execute("select * from ccinfo;")
dat = mycur.fetchall()
for val in dat:
i = val[0]
db_data[i] = list(val)
print(db_data)
for i in range(TC):
thr[i] = threading.Thread(target=print_time)
thr[i].start()
time.sleep(1)
for i in range(TC):
thr[i].join()
```
Simply add this <meta http-equiv="refresh" content="5"> to your HTML in the head
I want to pass the data from user input in the template create_proposal.html. The form is inside a dynamically generated table by JavaScript. Each row has cells that have input. The table inside create_proposal.html looks like:
<table id="empTable" class="table-striped" border="1" cellmargin="100px" cellpadding="0px"cellspacing="5px">
<tr>
<th>
<h5></h5>
</th>
<th>
<h5>No.</h5>
</th>
<th>
<h5>Part no.</h5>
</th>
<th style="width:30vw">
<h5>Description</h5>
</th>
<th>
<h5>Quantity</h5>
</th>
<th>
<h5>Unit Market price</h5>
</th>
<th>
<h5>Markup percentage</h5>
</th>
</tr>
</table>
And the script that generates the rows:
<script>
// ARRAY FOR HEADER.
var arrHead = new Array();
arrHead = ['', 'No.', 'Part no.', 'Description', 'Quantity', 'Unit market price', 'Markup percentage'];
// ADD A NEW ROW TO THE TABLE.s
function addRow() {
var empTab = document.getElementById('empTable');
var rowCnt = empTab.rows.length; // GET TABLE ROW COUNT.
var tr = empTab.insertRow(rowCnt); // TABLE ROW.
tr = empTab.insertRow(rowCnt);
for (var c = 0; c < arrHead.length; c++) {
var td = document.createElement('td'); // TABLE DEFINITION.
td = tr.insertCell(c);
if (c == 0) { // FIRST COLUMN.
// ADD A BUTTON.
var button = document.createElement('input');
// SET INPUT ATTRIBUTE.
button.setAttribute('type', 'button');
button.setAttribute('value', 'Remove');
button.setAttribute('class', 'btn btn-danger');
// ADD THE BUTTON's 'onclick' EVENT.
button.setAttribute('onclick', 'removeRow(this)');
td.appendChild(button);
}
else if(c == 1){
var ele = document.createElement('input');
ele.setAttribute('type', 'number');
ele.setAttribute('id', 'id_item_no');
ele.setAttribute('name', 'item_no');
td.appendChild(ele);
}
else if(c == 2){
var ele = document.createElement('input');
ele.setAttribute('type', 'text');
ele.setAttribute('id', 'id_part_no');
ele.setAttribute('name', 'part_no');
td.appendChild(ele);
}
else if(c == 3){
var ele = document.createElement('input');
ele.setAttribute('type', 'text');
ele.setAttribute('id', 'id_description');
ele.setAttribute('name', 'description');
td.appendChild(ele);
}
else if(c == 4){
var ele = document.createElement('input');
ele.setAttribute('type', 'number');
ele.setAttribute('id', 'id_quantity');
ele.setAttribute('name', 'quantity');
td.appendChild(ele);
}
else if(c == 5){
var ele = document.createElement('input');
ele.setAttribute('type', 'number');
ele.setAttribute('id', 'id_unit_market_price');
ele.setAttribute('name', 'unit_market_price');
td.appendChild(ele);
}
else if(c == 6){
var ele = document.createElement('input');
ele.setAttribute('type', 'number');
ele.setAttribute('name', 'markup_percentage');
ele.setAttribute('id', 'id_markup_percentage');
td.appendChild(ele);
}
}
}
// DELETE TABLE ROW.
function removeRow(oButton) {
var empTab = document.getElementById('empTable');
empTab.deleteRow(oButton.parentNode.parentNode.rowIndex); // BUTTON -> TD -> TR.
}
</script>
in my views.py I call a function called merge() which accepts parameters from the user input. The function in view.py that calls the merge() function looks like:
def resultPage(request):
if request.method == 'POST':
form =createNewFinancial(request.POST)
if form.is_valid():
name = form.cleaned_data['file_name']
organization = form.cleaned_data['organization_name']
project_type = form.cleaned_data['project_type']
reference = form.cleaned_data['reference_number']
our_ref_no = form.cleaned_data['our_reference_number']
date = form.cleaned_data['date']
item_no = form.cleaned_data['item_no']
part_no = form.cleaned_data['part_no']
description = form.cleaned_data['description']
quantity = form.cleaned_data['quantity']
unit_market_price = form.cleaned_data['unit_market_price']
markup_percentage = form.cleaned_data['markup_percentage']
merge(name, organization, project_type, reference, our_ref_no, date, item_no, part_no, description, quantity, unit_market_price, markup_percentage)
return render(request, 'result.html')
and the merge() function:
def merge(name, organization, project_type, reference, our_reference, date, item_no, part_no, description, quantity, unit_market_price, markup_percentage):
template = 'master.docx'
document = MailMerge(template)
unit_price = calculateUitPrice(unit_market_price, markup_percentage)
total_price = quantity * unit_price
document.merge(
organization = organization,
project_type = project_type,
reference = reference,
our_ref_no = our_reference,
date = date,
)
item_table = [{
'item_no' : str(item_no),
'part_no' : str(part_no),
'description' : str(description),
'quantity' : str(quantity),
'unit_price' : str(unit_price),
'total_price' : str(total_price)
},]
document.merge_rows('item_no', item_table)
document.write(name+'.docx')
there are multiple rows that has input fields with the same id. I wanted to pass the values in an array but do not know how. Any working solution would also be nice.
Thanks
i am following this Guide in an effort to connect to a sharepoint site with python and grab some data using the REST api. however, i keep having trouble with the JSON decoder in order to read the data like it suggests in the guide.
I have followed the Guide to the letter and keep having the same issues. I tried to change the headers to headers = {'content-type':'application/json'}as it suggests on another question asked on here; but nothing has worked.
This is what i have so far much like the guide suggests:
import requests
from requests_ntlm import HttpNtlmAuth
headers = {"accept": "application/json;odata=verbose"}
response = requests.get("http://Sharepointsite/_api/web/", auth=HttpNtlmAuth('User','Pass'),headers=headers)
print(response.content)
print(response.json()["d"]["CustomMasterUrl"])
This is the error message that i get:
Traceback (most recent call last):
File "C:/Users/User/MyProjects/ProductivityTracking/SharepointConnection/Sharepoint Integration.py", line 9, in <module>
print (response.json()["d"]["CustomMasterUrl"])
File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\models.py", line 897, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 2)
if you guys can point me in the right direction to start trouble shooting this, that would be awesome - i searched everywhere on stack and beyond.
Additional Info - the response content:
b'\r\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\r\n\t"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\r\n<html dir="ltr" lang="en-US">\r\n<head><meta name="GENERATOR" content="Microsoft SharePoint" /><meta http-equiv="Content-type" content="text/html; charset=utf-8" /><meta http-equiv="X-UA-Compatible" content="IE=10" /><meta http-equiv="Expires" content="Fri, 11 Oct 2019 15:09:01 GMT" /><meta name="msapplication-TileImage" content="/_layouts/15/images/SharePointMetroAppTile.png" /><meta name="msapplication-TileColor" content="#0072C6" /><link rel="shortcut icon" href="/_layouts/15/images/favicon.ico?rev=23" type="image/vnd.microsoft.icon" id="favicon" />\r\n<script type=\'text/javascript\'>\r\n// <![CDATA[\r\nvar url = window.location.href; var g_initUrl=\'\';\r\nvar hashSaverUrl = \'\';var keyName = \'MDSLoginAllowedUrl\';var idx = url.indexOf(\'&\' + keyName + \'=\');\r\nif (idx != -1) {\r\n var idx2 = url.indexOf(\'&\', idx + 1);\r\n if (idx2 == -1)\r\n idx2 = url.length;\r\n hashSaverUrl = url.substring(idx + keyName.length + 2, idx2);\r\n hashSaverUrl = decodeURIComponent(hashSaverUrl);\r\n}\r\nif (!hashSaverUrl || hashSaverUrl == \'\') {\r\n var g_MDSStartTime = new Date();\r\n var g_MinimalDownload = true;var g_mdsReady=false;var isStartPlt1 = true;var startDate = g_MDSStartTime.valueOf().toString();\r\n var skipOverlay=true;var startRenderComplete=false;var initContentComplete=false;\r\n var hashParts=window.location.hash.substr(1).split(\'#\');var ch=hashParts[0];var localAnc=null; \r\n for (var i=1;i<hashParts.length;i++){\r\n var s=hashParts[i];\r\n if (s.indexOf(\'=\') == -1) {\r\n localAnc=s; \r\n break;\r\n }\r\n }\r\n\r\n var requestUrlFull;\r\n if (ch.length >= 2 && ch[0] === \'/\' && ch[1] === \'/\')\r\n {\r\n if (ch[2] !== \'/\')\r\n {\r\n g_initUrl = ch.substr(1);\r\n requestUrlFull = window.location.hash.substr(2);\r\n }\r\n } else if (typeof(ch) != \'undefined\' && ch.length >= 1 && ch[0] === \'/\')\r\n {\r\n var loc = window.location.pathname;\r\n var pos = loc.indexOf(\'/_layouts/15/start.aspx\');\r\n var hash = window.location.hash.substr(1);\r\n var hPos = hash.indexOf(\'#\');\r\n hPos = hPos >= 0 ? hPos : hash.length;\r\n g_initUrl = loc.substr(0, pos) + ch;\r\n requestUrlFull = g_initUrl + hash.substr(hPos);\r\n }\r\n\r\n if(g_initUrl){\r\n var delim=ch.indexOf(\'?\')!=-1 ? \'&\' : \'?\';\r\n var xhr=new XMLHttpRequest();\r\n xhr.open(\'GET\',g_initUrl+delim+\'AjaxDelta=1&isStartPlt1=\' + startDate, true);\r\n xhr.setRequestHeader(\'Pragma\', \'SharePointAjaxDelta=|SITES|SANDBOX:|SITES|SANDBOX|_CATALOGS|MASTERPAGE|SEATTLE.MASTER:2.15.0.0.0.15.0.5131.1000.0.FALSE.:en-US:en-US:RW\');\r\n xhr.onreadystatechange=function(){\r\n if(xhr.readyState==4){\r\n if(g_mdsReady){\r\n asyncDeltaManager._navigate(requestUrlFull, localAnc);}\r\n else\r\n {g_mdsReady=true;}}};\r\n xhr.send(null);}\r\n else\r\n {g_mdsReady=true;}\r\n}\r\n\r\n// ]]>\r\n</script>\r\n<link rel="stylesheet" type="text/css" href="/_layouts/15/1033/styles/Themable/corev15.css?rev=2bpHeX9U8DH09TB5zpJcsQ%3D%3D"/>\n<script type="text/javascript" src="/_layouts/15/init.js?rev=ZwTQYqYlNTyyuMWaLlhwSg%3D%3D"></script>\n<script type="text/javascript" src="/ScriptResource.axd?d=ideow4fpAMtT1LU3KRk4QdrhD1jlPBAePc9i8Ib6lUnFTPWZBlpLxAiBo8ORwOMMJgN20_t9vRkidn1TCfn8SlPTG2UqSNGHdiXmH-2qG7qawwjHGYQutflvf9Bq4OfLRdTYGOD6T8DyvDQ6rrD3oPhj_zf3sNcoJxJOKX0a2n2TdJGcEtmFj3kTppa6_7PE0&t=ffffffffc60ca17c"></script>\n<script type="text/javascript" src="/_layouts/15/blank.js?rev=ZaOXZEobVwykPO9g8hq%2F8A%3D%3D"></script>\n<script type="text/javascript" src="/_layouts/15/start.js?rev=RJ1wZoVJ%2F7xfKjfBnjaWng%3D%3D"></script>\n<script type="text/javascript">RegisterSod("initstrings.js", "\\u002f_layouts\\u002f15\\u002f1033\\u002finitstrings.js?rev=S11vfGURQYVuACMEY0tLTg\\u00253D\\u00253D");</script>\n<script type="text/javascript">RegisterSod("strings.js", "\\u002f_layouts\\u002f15\\u002f1033\\u002fstrings.js?rev=0Q8SquDYHrVJnF3A1pfsSQ\\u00253D\\u00253D");RegisterSodDep("strings.js", "initstrings.js");</script>\n<script type="text/javascript">RegisterSod("sp.init.js", "\\u002f_layouts\\u002f15\\u002fsp.init.js?rev=jvJC3Kl5gbORaLtf7kxULQ\\u00253D\\u00253D");</script>\n<script type="text/javascript">RegisterSod("sp.res.resx", "\\u002f_layouts\\u002f15\\u002fScriptResx.ashx?culture=en\\u00252Dus\\u0026name=SP\\u00252ERes\\u0026rev=yNk\\u00252FhRzgBn40LJVP\\u00252BqfgdQ\\u00253D\\u00253D");</script>\n<script type="text/javascript">RegisterSod("sp.ui.dialog.js", "\\u002f_layouts\\u002f15\\u002fsp.ui.dialog.js?rev=3Oh2QbaaiXSb7ldu2zd6QQ\\u00253D\\u00253D");RegisterSodDep("sp.ui.dialog.js", "sp.init.js");RegisterSodDep("sp.ui.dialog.js", "sp.res.resx");</script>\n<script type="text/javascript">RegisterSod("core.js", "\\u002f_layouts\\u002f15\\u002fcore.js?rev=GpU7vxyOqzS0F9OfEX3CCw\\u00253D\\u00253D");RegisterSodDep("core.js", "strings.js");</script>\n<script type="text/javascript">RegisterSod("menu.js", "\\u002f_layouts\\u002f15\\u002fmenu.js?rev=cXv35JACAh0ZCqUwKU592w\\u00253D\\u00253D");</script>\n<script type="text/javascript">RegisterSod("mQuery.js", "\\u002f_layouts\\u002f15\\u002fmquery.js?rev=VYAJYBo5H8I3gVSL3MzD6A\\u00253D\\u00253D");</script>\n<script type="text/javascript">RegisterSod("callout.js", "\\u002f_layouts\\u002f15\\u002fcallout.js?rev=ryx2n4ePkYj1\\u00252FALmcsXZfA\\u00253D\\u00253D");RegisterSodDep("callout.js", "strings.js");RegisterSodDep("callout.js", "mQuery.js");RegisterSodDep("callout.js", "core.js");</script>\n<script type="text/javascript">RegisterSod("clienttemplates.js", "\\u002f_layouts\\u002f15\\u002fclienttemplates.js?rev=OJfMNjaofDqyBzPvjPo3XA\\u00253D\\u00253D");RegisterSodDep("clienttemplates.js", "initstrings.js");</script>\n<script type="text/javascript">RegisterSod("sharing.js", "\\u002f_layouts\\u002f15\\u002fsharing.js?rev=XxxHIxIIc8BsW9ikVc6dgA\\u00253D\\u00253D");RegisterSodDep("sharing.js", "strings.js");RegisterSodDep("sharing.js", "mQuery.js");RegisterSodDep("sharing.js", "clienttemplates.js");RegisterSodDep("sharing.js", "core.js");</script>\n<script type="text/javascript">RegisterSod("suitelinks.js", "\\u002f_layouts\\u002f15\\u002fsuitelinks.js?rev=REwVU5jSsadDdOZlCx4wpA\\u00253D\\u00253D");RegisterSodDep("suitelinks.js", "strings.js");RegisterSodDep("suitelinks.js", "core.js");</script>\n<link type="text/xml" rel="alternate" href="/sites/sandbox/_vti_bin/spdisco.aspx" /></head>\r\n<body>\r\n <div id="imgPrefetch" style="display:none">\r\n</div>\r\n\r\n <noscript><div class=\'noindex\'>You may be trying to access this site from a secured browser on the server. Please enable scripts and reload this page.</div></noscript>\r\n \r\n <form method="post" action="./start.aspx" id="aspnetForm" onsubmit="if (typeof(_spFormOnSubmitWrapper) == "function") return _spFormOnSubmitWrapper();">\r\n<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTY1NDU2MTA1Mg9kFgJmD2QWAgIBD2QWAgIJDxYCHghvbnN1Ym1pdAVSaWYgKHR5cGVvZihfc3BGb3JtT25TdWJtaXRXcmFwcGVyKSA9PSAiZnVuY3Rpb24iKSByZXR1cm4gX3NwRm9ybU9uU3VibWl0V3JhcHBlcigpO2Rk82P14L36F04gkzB9Q1Z5k5kq+AtfmPqNYl/2Da94T8s=" />\r\n\r\n\r\n<script type="text/javascript">\r\n//<![CDATA[\r\nvar g_presenceEnabled = true;\nvar g_wsaEnabled = false;\nvar g_wsaQoSEnabled = false;\nvar g_wsaQoSDataPoints = [];\nvar g_wsaLCID = 1033;\nvar g_wsaListTemplateId = null;\nvar _fV4UI=true;var _spPageContextInfo = {webServerRelativeUrl: "\\u002fsites\\u002fsandbox", webAbsoluteUrl: "http:\\u002f\\u002fhemportal.hem.jmhuber.com\\u002fsites\\u002fsandbox", siteAbsoluteUrl: "http:\\u002f\\u002fhemportal.hem.jmhuber.com\\u002fsites\\u002fsandbox", serverRequestPath: "\\u002f_layouts\\u002f15\\u002fstart.aspx", layoutsUrl: "_layouts\\u002f15", webTitle: "", webTemplate: "", tenantAppVersion: "none", isAppWeb: false, Has2019Era: true, webLogoUrl: "_layouts\\u002f15\\u002fimages\\u002fsiteicon.png", webLanguage: 1033, currentLanguage: 1033, currentUICultureName: "en-US", currentCultureName: "en-US", clientServerTimeDelta: new Date("2019-09-11T15:09:01.6585779Z") - new Date(), siteClientTag: "0$$15.0.5131.1000", crossDomainPhotosEnabled:false, webUIVersion:15, webPermMasks:{High:0,Low:0}, pagePersonalizationScope:1, alertsEnabled:true, customMarkupInCalculatedFieldDisabled: true, siteServerRelativeUrl: "\\u002fsites\\u002fsandbox", allowSilverlightPrompt:\'True\'};var MSOWebPartPageFormName = \'aspnetForm\';//]]>\r\n</script>\r\n\r\n<script src="/_layouts/15/blank.js?rev=ZaOXZEobVwykPO9g8hq%2F8A%3D%3D" type="text/javascript"></script>\r\n<script type="text/javascript">\r\n//<![CDATA[\r\nif (typeof(DeferWebFormInitCallback) == \'function\') DeferWebFormInitCallback();//]]>\r\n</script>\r\n\r\n<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="A31D3FD9" />\r\n\t<script type="text/javascript"> var submitHook = function () { return false; }; theForm._spOldSubmit = theForm.submit; theForm.submit = function () { if (!submitHook()) { this._spOldSubmit(); } }; </script>\r\n\t<span id="DeltaSPWebPartManager"></span>\r\n\t\r\n\t<span id="DeltaDelegateControls"></span>\r\n<div id="TurnOnAccessibility" style="display:none" class="s4-notdlg noindex">\r\n\t<a id="linkTurnOnAcc" href="#" class="ms-accessible ms-acc-button" onclick="SetIsAccessibilityFeatureEnabled(true);UpdateAccessibilityUI();document.getElementById(\'linkTurnOffAcc\').focus();return false;">Turn on more accessible mode</a>\r\n</div>\r\n<div id="TurnOffAccessibility" style="display:none" class="s4-notdlg noindex">\r\n\t<a id="linkTurnOffAcc" href="#" class="ms-accessible ms-acc-button" onclick="SetIsAccessibilityFeatureEnabled(false);UpdateAccessibilityUI();document.getElementById(\'linkTurnOnAcc\').focus();return false;">Turn off more accessible mode</a>\r\n</div>\r\n<div class="s4-notdlg s4-skipribbonshortcut noindex">\r\n\tSkip Ribbon Commands\r\n</div>\r\n<div class="s4-notdlg noindex">\r\n\tSkip to main content\r\n</div>\r\n<div id="TurnOffAnimation" style="display:none;" class="s4-notdlg noindex">\r\n\t<a id="linkTurnOffAnimation" href="#" class="ms-accessible ms-acc-button" onclick="ToggleAnimationStatus();return false;">Turn off Animations</a>\r\n</div>\r\n<div id="TurnOnAnimation" style="display:none;" class="s4-notdlg noindex">\r\n\t<a id="linkTurnOnAnimation" href="#" class="ms-accessible ms-acc-button" onclick="ToggleAnimationStatus();return false;">Turn on Animations</a>\r\n</div>\r\n<a id="HiddenAnchor" href="javascript:;" style="display:none;"></a>\r\n<div id="suiteBar" class="ms-dialogHidden noindex">\r\n\t<div id="suiteBarLeft">\r\n\t\t<div class="ms-table ms-fullWidth">\r\n\t\t\t<div class="ms-tableRow">\r\n\t\t\t\t<div class="ms-tableCell ms-verticalAlignMiddle">\r\n\t\t\t\t\t\r\n\t\t\t\t</div>\r\n\t\t\t\t<div id="DeltaSuiteLinks" class="ms-core-deltaSuiteLinks">\r\n\r\n</div>\r\n\t\t\t</div>\r\n\t\t</div>\r\n\t</div>\r\n\t<div id="suiteBarRight">\r\n\t\t<div id="DeltaSuiteBarRight" class="ms-core-deltaSuiteBarRight">\r\n\r\n</div>\r\n\t</div>\r\n</div>\r\n\t\t<div id="ms-hcTest"></div>\r\n\t\t<div id="s4-ribbonrow">\r\n\t\t<div id="globalNavBox" class="noindex">\r\n<div id="ribbonBox">\r\n\t<div id="s4-ribboncont">\r\n\t\t<div id="DeltaSPRibbon">\r\n\r\n</div>\r\n\t</div>\r\n\t<span id="DeltaSPNavigation"></span>\r\n</div>\r\n<div id="DeltaWebPartAdderUpdatePanelContainer" class="ms-core-webpartadder">\r\n\r\n</div>\r\n\t\t</div>\r\n\t\t</div>\r\n\t\t<div id="s4-workspace" class="ms-core-overlay">\r\n\t\t<div id="s4-bodyContainer">\r\n\t\t<div id="s4-titlerow"\r\n\t\t\tclass="ms-dialogHidden s4-titlerowhidetitle">\r\n\t\t<div id="titleAreaBox"\r\n\t\t\tclass="ms-noList ms-table ms-core-tableNoSpace">\r\n\t\t<div id="titleAreaRow"\r\n\t\t\tclass="ms-tableRow">\r\n<div id="siteIcon" class="ms-tableCell ms-verticalAlignTop">\r\n\t<div id="DeltaSiteLogo">\r\n\r\n</div>\r\n</div>\r\n\t\t\t<div class="ms-breadcrumb-box ms-tableCell ms-verticalAlignTop">\r\n\t\t\t\t<div\r\n\t\t\t\t\tclass="ms-breadcrumb-top">\r\n<div class="ms-breadcrumb-dropdownBox" style="display:none;">\r\n<span id="DeltaBreadcrumbDropdown"></span>\r\n</div>\r\n<div id="DeltaTopNavigation" class="ms-displayInline ms-core-navigation" role="navigation">\r\n\r\n</div>\r\n\t\t\t\t</div>\r\n<h1 id="pageTitle" class="ms-core-pageTitle">\r\n <span id="DeltaPlaceHolderPageTitleInTitleArea"></span>\r\n <div id="DeltaPlaceHolderPageDescription" class="ms-displayInlineBlock ms-normalWrap">\r\n\r\n</div>\r\n</h1>\r\n\t\t\t</div>\r\n\t\t\t<div class="ms-tableCell ms-verticalAlignTop">\r\n<div id="DeltaPlaceHolderSearchArea" class="ms-mpSearchBox ms-floatRight">\r\n\r\n</div>\r\n\t\t\t</div>\r\n\t\t</div>\r\n\t\t</div>\r\n\t\t</div>\r\n\t\t<div id="contentRow">\r\n<div id="sideNavBox"\r\n\t class="ms-dialogHidden ms-forceWrap ms-noList">\r\n <div id="DeltaPlaceHolderLeftNavBar" class="ms-core-navigation" role="navigation">\r\n\r\n</div>\r\n</div>\r\n<div id="contentBox"\r\n aria-live="polite" aria-relevant="all">\r\n <div id="notificationArea" class="ms-notif-box"></div>\r\n\t<div id="DeltaPageStatusBar">\r\n\r\n</div>\r\n\t<div id="DeltaPlaceHolderMain">\r\n\r\n</div>\r\n</div>\r\n<div id="DeltaFormDigest">\r\n\r\n</div>\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t</div>\r\n\t\t</div>\r\n\t\t</div>\r\n\r\n\r\n<script type="text/javascript">\r\n//<![CDATA[\r\n\r\nvar filesExist = true;\r\nif (typeof(initJsLoaded) === \'undefined\') { filesExist = false; }\r\nelse if (typeof(Sys) === \'undefined\') { filesExist = false; }\r\nelse if (typeof(Sys.WebForms) === \'undefined\') { filesExist = false; }\r\nelse if (typeof(startJsLoaded) === \'undefined\') { filesExist = false; }\r\nvar sessionStorageEnabled = window.sessionStorage != null;\r\nif (!filesExist) {\r\n if (!sessionStorageEnabled || window.sessionStorage[\'spFilesExist\'] === \'false\'){\r\n if (\'undefined\' != typeof(g_initUrl) && null != g_initUrl && \'\' != g_initUrl)\r\n {\r\n try\r\n {\r\n if (sessionStorageEnabled) \r\n {\r\n window.sessionStorage[\'spFilesExist\'] = \'true\';\r\n }\r\n }\r\n catch (e) {}\r\n var tempAnchor = document.createElement(\'a\');\r\n tempAnchor.href = g_initUrl;\r\n var redir = tempAnchor.href;\r\n tempAnchor = null;\r\n window.location.href=redir;\r\n }\r\n }else{\r\n try\r\n {\r\n window.sessionStorage[\'spFilesExist\'] = \'false\';\r\n window.location.reload(true);\r\n }\r\n catch (e) {}\r\n }\r\n} else {\r\n if (sessionStorageEnabled)\r\n {\r\n window.sessionStorage[\'spFilesExist\'] = \'true\';\r\n }\r\n}\r\nvar workingOnIt = \'Working on it...\';var _spFullDownloadList = [\'closeconnection\', \'download\', \'signout\', \'xlviewer\', \'wordviewer\', \'wordeditor\', \'powerpoint\', \'powerpointframe\', \'onenote\', \'visiowebaccess\', \'storefront\', \'wopiframe\', \'appredirect\', \'wfstart\'];\nif (\'undefined\' != typeof(AsyncDeltaManager$onError)) window.onerror = AsyncDeltaManager$onError;\nvar _fV4UI = true;var origMP = \'|SITES|SANDBOX:|SITES|SANDBOX|_CATALOGS|MASTERPAGE|SEATTLE.MASTER:2.15.0.0.0.15.0.5131.1000.0.FALSE.:en-US:en-US:RW\';var phMain = \'DeltaPlaceHolderMain\';var g_AjaxDeltaList = [{id:\'DeltaPlaceHolderAdditionalPageHead\', container:false},{id:\'DeltaSPWebPartManager\', container:true},{id:\'DeltaDelegateControls\', container:true},{id:\'DeltaSuiteLinks\', container:true},{id:\'DeltaSuiteBarRight\', container:true},{id:\'DeltaSPRibbon\', container:true},{id:\'DeltaSPNavigation\', container:true},{id:\'DeltaWebPartAdderUpdatePanelContainer\', container:true},{id:\'DeltaSiteLogo\', container:true},{id:\'DeltaBreadcrumbDropdown\', container:true},{id:\'DeltaTopNavigation\', container:true},{id:\'DeltaPlaceHolderPageTitleInTitleArea\', container:true},{id:\'DeltaPlaceHolderPageDescription\', container:true},{id:\'DeltaPlaceHolderSearchArea\', container:true},{id:\'DeltaPlaceHolderLeftNavBar\', container:true},{id:\'DeltaPageStatusBar\', container:true},{id:\'DeltaPlaceHolderMain\', container:true},{id:\'DeltaFormDigest\', container:true},{id:\'DeltaPlaceHolderUtilityContent\', container:true}];\n\r\nfunction submitHook() {{return asyncDeltaManager._onFormSubmit();}}\r\nfunction _startOnSubmitStatement() {{return asyncDeltaManager._doSubmitStatements();}}\r\nfunction WebForm_OnSubmit() {{ return asyncDeltaManager._doSubmitStatements(); }}\r\n\r\nif (typeof(hashSaverUrl) != \'undefined\' && hashSaverUrl && hashSaverUrl != \'\') {\r\n if ( (function(u, d) {\r\n var idxDb = u.indexOf(\'//\');\r\n if (-1 != idxDb) {\r\n var idxDe = u.indexOf(\'/\', idxDb+2);\r\n if (-1 == idxDe) idxDe = u.length;\r\n var D = u.substring(idxDb+2, idxDe);\r\n if (d.toUpperCase() != D.toUpperCase()) return true;\r\n }\r\n return false;\r\n }) (hashSaverUrl, document.location.host)) { hashSaverUrl = \'/\';}\r\n window.location.replace(STSPageUrlValidation(hashSaverUrl));\r\n}\r\nvar g_clientIdDeltaPlaceHolderMain = "DeltaPlaceHolderMain";\r\nvar g_clientIdDeltaPlaceHolderPageTitleInTitleArea = "DeltaPlaceHolderPageTitleInTitleArea";\r\nvar g_clientIdDeltaPlaceHolderUtilityContent = "DeltaPlaceHolderUtilityContent";\r\n//]]>\r\n</script>\r\n</form>\r\n\t<span id="DeltaPlaceHolderUtilityContent"></span>\r\n\t<script type="text/javascript">// <![CDATA[ \n\r\n\r\n\t\tvar g_Workspace = "s4-workspace";\r\n\t// ]]>\r\n</script>\r\n</body>\r\n</html>\r\n'
Check the steps below.
1.Install requests.
pip install requests
2.Install requests_ntlm.
pip install requests_ntlm
3.Make the username(domain\username) and password are right, and run the code as below.
import requests
from requests_ntlm import HttpNtlmAuth
headers = {'accept': 'application/json;odata=verbose'}
r = requests.get("http://sp2013/sites/team/_api/web", auth=HttpNtlmAuth('domain\\admin', 'password'), headers=headers)
print(r.json()["d"]["CustomMasterUrl"])
I am having problems with writing to my HTML file.
I want to be able to make my code place what I have written in HTML, but my code will only do it when I do not have any While/If statements in this definition. If I do have Whiles/Ifs, my HTML file will simply just become blank. I have no idea why this happens, and I can't seem to find a workaround.
Is there any way to use Whiles/Ifs without making my code delete everything in my file, and instead make it write what I want to in there?
def invoice_creator_window():
global total_cost, total_cost_list, list_of_items, invoice_created
invoice_created = Toplevel()
invoice_created.focus_set()
invoice_created.resizable(width = True, height = False)
invoice_created.title("Invoice Created")
invoice_created.geometry("300x300")
invoice_created.geometry("+400+400")
invoice_created.configure(bg = "limegreen")
currentDisplay = 10
print(total_cost, total_cost_list, list_of_items)
done = Label(invoice_created, text = "Items have been purchased. Invoice has been created. Please check this program's file location.")
invoice_created = Button(invoice_created, text = "Done", bg = "white", command = close_window)
#
done.grid(row = 1, column = 1, padx = 7.5, pady = space_between)
invoice_created.grid(row = 2, column = 1, padx = 7.5, pady = space_between)
# This section is for the invoice creation with HTML.
html_formatting_start = """<!DOCTYPE html>
<html>
<head>
<title>Games R Us - Invoice</title>
</head>
<body>
<style>
body {background-color: #F7D358;}
h1 {color: #775A03;}
p {color: ; border: 1px solid #775A03; padding: 15px; width: 650px}
</style>
<center>
<h1>Games R Us - Invoice Document</h1>
"""
counter = 0
while len(list_of_items) > 0:
global html_formatting_mid
print(counter)
html_formatting_mid = ("""
<h3>
<p>
<img src="https://steamcdn-a.akamaihd.net/steam/apps/211420/header.jpg?t=1483694369"</img>
<br>""" + str(list_of_items[counter]) + """<br>
<i>$""" + str(total_cost_list[counter]) + """ AUD</i>
</p>
</h3>
""")
if counter >= len(list_of_items) - 1:
return
else:
counter += 1
html_formatting_end = """
<h2>In Total: $""" + str(total_cost) +""" AUD</h2>
<br>
<b>Information Grabbed from These Links: </b>
Steam's New Releases [LIVE] -
Steam's Top Sellers [LIVE] -
Umart's Headphones [PRE-DOWNLOADED] -
Umart's Microphones [PRE-DOWNLOADED]
</center>
</body>
</html>"""
invoice_creation = open(invoice_file, "w")
invoice_creation.write(html_formatting_start)
invoice_creation.write(html_formatting_mid)
invoice_creation.write(html_formatting_end)
invoice_creation.close()
#############################################################################
button_buy = Button(welcome_window, text = "Buy", fg = "white", bg = "goldenrod", font = gui_font_10,
command = invoice_creator_window)
Note: "total_cost_list" and "list_of_items" are all lists. "total_cost" is a value. Do not worry too much about the context of these, but I wanted to clarify in case they might be affecting anything.
Here is a fixed version of your code in as simple a container as possible.
from tkinter import *
import webbrowser
root = Tk ()
space_between, invoice_file = 5, "Invoice.html"
total_cost, total_cost_list, list_of_items = 10, [1, 9], ["Something", "Something 2"]
def close_window (): root.destroy ()
def invoice_creator_window():
global total_cost, total_cost_list, list_of_items, invoice_created
invoice_created = Toplevel()
invoice_created.focus_set()
invoice_created.resizable(width = True, height = False)
invoice_created.title("Invoice Created")
invoice_created.geometry("300x300")
invoice_created.geometry("+400+400")
invoice_created.configure(bg = "limegreen")
currentDisplay = 10
print(total_cost, total_cost_list, list_of_items)
done = Label(invoice_created, text = "Items have been purchased. Invoice has been created.")
invoice_created = Button(invoice_created, text = "Done", bg = "white", command = close_window)
#
done.grid(row = 1, column = 1, padx = 7.5, pady = space_between)
invoice_created.grid(row = 2, column = 1, padx = 7.5, pady = space_between)
# This section is for the invoice creation with HTML.
html_formatting_start = """<!DOCTYPE html>
<html>
<head>
<title>Games R Us - Invoice</title>
</head>
<body>
<style>
body {background-color: #F7D358;}
h1 {color: #775A03;}
p {color: ; border: 1px solid #775A03; padding: 15px; width: 650px}
</style>
<center>
<h1>Games R Us - Invoice Document</h1>
"""
counter = 0
html_formatting_mid = ""
while len(list_of_items) > 0:
print(counter)
html_formatting_mid += """
<h3>
<p>
<img src="https://steamcdn-a.akamaihd.net/steam/apps/211420/header.jpg?t=1483694369"</img>
<br>""" + str(list_of_items[counter]) + """<br>
<i>$""" + str(total_cost_list[counter]) + """ AUD</i>
</p>
</h3>
"""
if counter >= len(list_of_items) - 1:
break
else:
counter += 1
html_formatting_end = """
<h2>In Total: $""" + str(total_cost) +""" AUD</h2>
<br>
<b>Information Grabbed from These Links: </b>
Steam's New Releases [LIVE] -
Steam's Top Sellers [LIVE] -
Umart's Headphones [PRE-DOWNLOADED] -
Umart's Microphones [PRE-DOWNLOADED]
</center>
</body>
</html>"""
invoice_creation = open(invoice_file, "w")
invoice_creation.write (html_formatting_start + html_formatting_mid + html_formatting_end)
invoice_creation.close ()
webbrowser.open (invoice_file)
#############################################################################
button_buy = Button(root, text = "Buy", fg = "white", bg = "goldenrod",
command = invoice_creator_window).pack ()
root.mainloop ()
I found a solution.
def invoice_creator_window():
global total_cost, total_cost_list, list_of_items, invoice_created
invoice_created = Toplevel()
invoice_created.focus_set()
invoice_created.resizable(width = True, height = False)
invoice_created.title("Invoice Created")
invoice_created.geometry("300x300")
invoice_created.geometry("+400+400")
invoice_created.configure(bg = "limegreen")
currentDisplay = 10
print(total_cost, total_cost_list, list_of_items)
done = Label(invoice_created, text = "Items have been purchased. Invoice has been created. Please check this program's file location.")
invoice_created = Button(invoice_created, text = "Done", bg = "white", command = close_window)
#
done.grid(row = 1, column = 1, padx = 7.5, pady = space_between)
invoice_created.grid(row = 2, column = 1, padx = 7.5, pady = space_between)
# This section is for the invoice creation with HTML.
html_formatting_start = """<!DOCTYPE html>
<html>
<head>
<title>Games R Us - Invoice</title>
</head>
<body>
<style>
body {background-color: #F7D358;}
h1 {color: #775A03;}
p {color: ; border: 1px solid #775A03; padding: 15px; width: 650px}
</style>
<center>
<h1>Games R Us - Invoice Document</h1>
"""
counter = 0
html_formatting_mid = ""
for items in list_of_items:
print(counter)
html_formatting_mid += ("""
<h3>
<p>
<img src="https://steamcdn-a.akamaihd.net/steam/apps/211420/header.jpg?t=1483694369"</img>
<br>""" + str(list_of_items[counter]) + """<br>
<i>$""" + str(total_cost_list[counter]) + """ AUD</i>
</p>
</h3>
""")
counter += 1
html_formatting_end = """
<h2>In Total: $""" + str(total_cost) +""" AUD</h2>
<br>
<b>Information Grabbed from These Links: </b>
Steam's New Releases [LIVE] -
Steam's Top Sellers [LIVE] -
Umart's Headphones [PRE-DOWNLOADED] -
Umart's Microphones [PRE-DOWNLOADED]
</center>
</body>
</html>"""
invoice_creation = open(invoice_file, "w")
invoice_creation.write(html_formatting_start)
invoice_creation.write(html_formatting_mid)
invoice_creation.write(html_formatting_end)
invoice_creation.close()
#############################################################################
button_buy = Button(welcome_window, text = "Buy", fg = "white", bg = "goldenrod", font = gui_font_10,
command = invoice_creator_window)
I went back to my older use of a for loop and tried using that. Except this time, I added html_formatting_mid += (""" to it, and then before the for loop, just added html_formatting_mid = "", like Minion Jim showed.
It works fully now.
A short answer would be, you could just write in append mode. open (filename, 'a') instead of open (filename, 'w'). This will add on to whatever is already in the file, so you may want to truncate it first.