I have been looking at JPCalderones example of using web.request with JSON which seems much like what I want.<div><br></div><div>One thing I am not clear about is if I get a lot of queries coming in more or less simultaneously and I am using cooperate to allow other functions to run, will I need to guard against my data in a list being overwritten by subsequent requests.</div>
<div><br></div><div>The way I see it the functions to read data and and store it in my list are in danger of impacting each other.</div><div><br></div><div>The response is being built cooperatively bit by bit to permit other functions to run so it could happen that the next request overwrites my list where the database query is being stored.</div>
<div><br></div><div>If this is a danger, then I need to prevent this, which seems to imply that I will need to block each request and not service another request until the previous one has completed.</div><div><br></div><div>
Have I got that right or am I way off target or have I missed the obvious</div><div><br></div><div>What would be good is to keep on servicing requests so that the response is good but keep the data integrity.</div><div><br>
</div><div>The test code I am using is JP&#39;s with some minor variations shown below. I hope it formats correctly.</div><div><br></div><div>Thanks for any help.</div><div><br></div><div>Regards</div><div><br></div><div>
John Aherne</div><div><br></div><div><div>#Asynchronous JSON</div><div>#Today in #twisted.web the topic of generating large JSON responses </div><div>#in a Twisted Web server came up. The problem was that the data being </div>
<div>#serialized into JSON was so large that the JSON serialization process</div><div>#itself would block the web server, preventing other requests from being </div><div>#serviced.</div><div>#</div><div>#The first solution that came up was to split the web server into two</div>
<div>#pieces, so that the URLs which could have these JSON responses were </div><div>#served by a different process than was serving the rest. This is a </div><div>#pretty decent solution, and it also provides the benefit of using extra</div>
<div>#CPU cores if there are any available. In this case, it complicated </div><div>#things a little since it meant sharing a session across two processes.</div><div>#So we went looking for another approach.</div><div>#</div>
<div>#It turns out that the json module supports incremental serialization.</div><div>#When I saw the JSONEncoder.iterencode method, I thought it would be </div><div>#great used in combination with cooperate to create a producer. This </div>
<div>#would let an application serialize a large structure to JSON without </div><div>#multiple processes, threads, or unreasonably blocking the reactor.</div><div>#</div><div>#Here&#39;s the little bit of glue necessary to make things work:</div>
<div>import cgi</div><div>from json import JSONEncoder</div><div>from twisted.enterprise import adbapi </div><div>from twisted.internet.task import cooperate</div><div><br></div><div>#db = sqlite3.connect(&#39;c:\\sqlite\\test.db&#39;)</div>
<div>#cur = db.cursor()</div><div>dbpool = adbapi.ConnectionPool(&quot;pyodbc&quot;,&quot;DSN=testsql&quot;,cp_reconnect=&#39;True&#39;)</div><div><br></div><div>class AsyncJSON(object):</div><div>    def __init__(self, value):</div>
<div>        self._value = value</div><div><br></div><div><br></div><div>    def beginProducing(self, consumer):</div><div>        #print &#39;value&#39;, self._value</div><div>        self._consumer = consumer</div><div>
        self._iterable = JSONEncoder().iterencode(self._value)</div><div>        #print &#39;iterable&#39;, self._iterable</div><div>        self._consumer.registerProducer(self, True)</div><div>        self._task = cooperate(self._produce())</div>
<div>        d = self._task.whenDone()</div><div>        d.addBoth(self._unregister)</div><div>        return d</div><div><br></div><div><br></div><div>    def pauseProducing(self):</div><div>        self._task.pause()</div>
<div><br></div><div><br></div><div>    def resumeProducing(self):</div><div>        self._task.resume()</div><div><br></div><div><br></div><div>    def stopProducing(self):</div><div>        self._task.stop()</div><div><br>
</div><div><br></div><div>    def _produce(self):</div><div>        for chunk in self._iterable:</div><div>            #print &#39;chunk&#39;, chunk</div><div>            self._consumer.write(chunk)</div><div>            yield None</div>
<div><br></div><div><br></div><div>    def _unregister(self, passthrough): </div><div>        self._consumer.unregisterProducer()</div><div>        return passthrough</div><div><br></div><div><br></div><div><br></div><div>
#By using the iterencode method, this avoids spending too much time</div><div>#generating json output at once. Instead, a little bit of the input </div><div>#will be serialized at a time, and each short resulting string is available</div>
<div>#from the iterator returned by iterencode.</div><div>#</div><div>#By using cooperate, the _produce generator will iterated in a way that</div><div>#lets it cooperate with the reactor and other event sources/handlers.</div>
<div>#A few chunks of json data will be written to the consumer, then execution </div><div>#will switch away to something else, then come back and a few more will</div><div>#be written, and so on.</div><div>#</div><div>#And by using the producer/consumer interface, if the HTTP client which</div>
<div>#issued the request doesn&#39;t read the results as fast as they&#39;re being</div><div>#generated, the server will stop generating new output until the client</div><div>#catches up.</div><div>#</div><div>#Altogether, this provides a very cool, efficient way to generate JSON</div>
<div>#output.</div><div>#</div><div>#Here&#39;s an example to make it easier to see how one might use AsyncJSON </div><div>#in a resource:</div><div>#</div><div>from twisted.web.resource import Resource</div><div>from twisted.web.server import NOT_DONE_YET</div>
<div>from twisted.web.server import Site</div><div>from twisted.internet import reactor</div><div><br></div><div>def read_pcodes(pcode, request):</div><div>    &quot;&quot;&quot; Read postcode data and premise data for single postocde   &quot;&quot;&quot;</div>
<div><br></div><div>    sql_mail = &quot;&quot;&quot;select rcmplc01.substreet,rcmplc01.street,</div><div>                         rcmplc01.sublocality, rcmplc01.locality,</div><div>                         rcmplc01.town, </div>
<div>                         rcmplc01.postcode,</div><div>                         rcmplc02.data</div><div>                         from rcmplc01</div><div>                         left outer join rcmplc02 </div><div>                         on rcmplc01.postcode = rcmplc02.postcode</div>
<div>                         where rcmplc01.postcode = ?</div><div>             &quot;&quot;&quot;</div><div>    pcode = pcode.strip().upper()</div><div>    def run():</div><div>        return dbpool.runQuery(sql_mail,(pcode,))</div>
<div>    d = run()</div><div>    d.addCallback(read_result, request)</div><div>    d.addErrback(read_failure,request)</div><div>    return d</div><div>    </div><div>def read_failure(o, request):</div><div>    print &#39;failure&#39;, str(o)</div>
<div>    request.finish()</div><div>    </div><div>    </div><div>def read_result(res, request):</div><div>    &quot;&quot;&quot; read result for postcode lookup. Build return list&quot;&quot;&quot;</div><div>    #print &#39;res&#39;, res</div>
<div>    print &#39;len res&#39;, len(res)</div><div>    my_list = []</div><div>    for item in res:</div><div><span class="Apple-tab-span" style="white-space:pre">        </span>my_list.append([item[0], item[1], item[2], item[3], item[4], item[5]])</div>
<div>    d = AsyncJSON(my_list).beginProducing(request)</div><div>    d.addCallback(lambda ignored: request.finish())</div><div>    d.addErrback(got_error, request)</div><div><br></div><div>root = Resource()</div><div>root.putChild(&quot;json&quot;, PostcodeFinder())</div>
<div>factory = Site(root)</div><div>reactor.listenTCP(8086, factory)</div><div>reactor.run()</div></div><div><br></div>