## python 3.x – How can I manipulate the data of a form in Django?

I am new to Django and I wanted to know how I can manipulate the data sent by the form.

I have the following form:

``````CreateNewUser class (forms.Form):

Name = forms.CharField (max_length = 200)
email = forms.EmailField ()
age = forms.DecimalField (min_value = 5, max_value = 120)
cpf = forms.CharField (label = "CPF", max_length = 11)
``````

View that represents the form:

``````Def request:
# Create an instance of the form so you can put it in templates
form = CreateNewUser ()
return render (request, & # 39; cadastro.html & # 39 ;, {& # 39; form & # 39 ;: form})
``````

I can not find any place that makes explicit how to access the data sent by the Django form.

## 3.x python – How to get the count of Google Cloud Datastore entities in a Class for a particular field value

I used to get the count of entities in a Class for a particular field value, as follows when I use the Google App Engine Python 2.7 NDB library as sample code below:

``````count = Product.query (Product.account_id == "myAccountID",
Product.category == "myCategory"). Count (99999)
``````

Now I'm switching to Python 3.7 using the Google Cloud Datastore API
https://googleapis.github.io/google-cloud-python/latest/datastore/index.html, unfortunately I could not find the COUNT function. I just found a way to get the total count for the whole entity in a Class using __Stat_Kind__, see the sample code below:

``````q = client.query (kind = "__ Stat_Kind__")
r = q.fetch (limit = 1)
account = 0
for x in r:
account = x["count"]
``````

The above example code will get the total count of entities for the Product Class, but if I want to get the total count in this Product Class with the value of the Category field equal to "myCategory"? Does anyone know how to do it?

Thank you!

## python 3.x – How to create an autocomplete method that looks for an existing trie in pythonn

I'm new to Python, I found different codes that implement trie, like this, for example:

``````from collections import default
TrieNode class:
def __init __ (self):
self.children = defaultdict (TrieNode)
self.isEnd = False
def insert (auto, word):
node = yo
for w in word:
node = node.children[w]
node.isEnd = True
def search (auto, word):
node = yo
for w in word:
if w in node.children:
node = node.children[w]
plus:
he came back []
# prefix coincidence
# traverse currnt node to all leaf nodes
result = []
self.traverse (node, list (word), result)
he came back [''.join(r) for r in result]

Def crossing (auto, root, prefix, result):
yes root.isEnd:
result.append (prefix[:])
for c, n in root.children.items ():
prefix.append (c)
self.traverse (n, prefix, result)
prefix.pop (-1)
yes __name__ == "__main__":
words = ['a', 'apple', 'angle', 'angel', 'bat', 'bats']
root = TrieNode ()
for w in words:
root.insert (w)

print (root.search (& # 39; an & # 39;)) # ['angle', 'angel']
print (root.search (& # 39; ap & # 39;)) # ['apple']

``````

What I am trying to achieve is to create a method that looks for an existing test and produces a list of suggestions, instead of creating a test every time, for example, the existing word for words = [‘a’, ‘apple’, ‘angle’, ‘angel’, ‘bat’, ‘bats’] is:
{& # 39; a & # 39 ;: {& # 39;& # 39;: & # 39;& # 39;, & # 39; p & # 39 ;: {& # 39; p & # 39 ;: {& # 39; l & # 39 ;: {& # 39; e & # 39 ;: {& # 39;& # 39;: & # 39;& # 39;}}}}}, & # 39; n & # 39 ;: {& # 39; g & # 39 ;: {& # 39; l & # 39 ;: {& # 39; e & # 39 ;: {& # 39;& # 39;: & # 39;& # 39;}}, & # 39; e & # 39 ;: {& # 39; l & # 39 ;: {& # 39;& # 39;: & # 39;& # 39 ;:}}}}}, & # 39; bat & # 39 ;: {& # 39;& # 39;: & # 39;& # 39;, & # 39; s & # 39 ;: {& # 39;& # 39;: & # 39;& # 39;}}}}}

What I was able to obtain through another code:

``````_end = & # 39; * & # 39;

# take a list of words
def make_trie (* words):
# create our root dict ()
trie = dict ()

for word in words:
# create a temporary dict based on our root
#dict object
temp_dict = trie

by letter in word:
# Update our temporary opinion and add our current
# letter and a sub-dictionary
temp_dict = temp_dict.setdefault (letter, {})

# If our word has ended, add {& # 39; * & # 39 ;: & # 39; * & # 39;}
# This tells us that our word is finished.
temp_dict[_end] = _end
back trie
def find_word (trie, word):
sub_trie = trie
mylist = []
by letter in word:
if letter in sub_trie:
sub_trie = sub_trie[letter]
mylist.append (letter)

plus:
false return
plus:
if _end in sub_trie:
return true
plus:
false return

# Test our creation trie
trie = make_trie (& # 39 ;, & # 39; apple & # 39 ;, & # 39; angle & # 39 ;, & # 39; angel & # 39 ;, & # 39; bat & # 39 ;, & # 39; bats & # 39;)
# print our new trie
print (trie)
find = find_word (trie, "apple")
print (find)

``````

## python 3.x – Access a data in a data structure

I am very new to Python, but with experience in other languages.
My problem arises when trying to use a module to read DBF files; and that I still do not assimilate the Python data structures.
The example of use that this module brings is:

``````from dbfread import DBF
for record in DBF ('people.dbf'):
print (record)
``````

Resulting…

``````OrderedDict ([('NAME', 'Alice'), ('BIRTHDATE', datetime.date(1987, 3, 1))])
OrderedDict ([('NAME', 'Bob'), ('BIRTHDATE', datetime.date(1980, 11, 12))])
``````

Where NAME and BIRTHDATE, are the field names of 'people.dbf'.
'Alice' and datetime.date (1987, 3, 1) are the values ​​of those fields, in the first record.
My problem is that I do not know how to reference these values ​​so that, in each iteration, I assign them to variables.
I mean, something like …

``````name = record.OrderedDict ('NAME') # that the variable name is assigned 'Alice'
date = record.OrderedDict ('BIRTHDATE') # that the date variable assigns datetime.date (1987, 3, 1)
``````

The module loads a single record for each iteration. That is, it does not load all the records in a structure that can then be traversed.
Only the last record read is available in each iteration.

## Python 3.x: you need to print the list from top to bottom instead of from bottom to top

The ATM program needs to keep track of the last 5 transactions. updates but prints the most recent transaction at the bottom instead of at the top.

Transactions is an empty list at the beginning of the program, starts empty and fills up as the program is used.

``````If option == 5:
yes len (transactions) <=0:
print("No History")
if len(transactions) > 5:
lower_bound = int (len (transactions)) - 5
upper_bound = lower_bound + 5
transaction_counter = 1
for the element in the range (lower_bound, upper_bound):
print (str (transaction_counter) + transactions[element])
transaction_counter = transaction_counter + 1
plus:
transaction_counter = 1
for the element in the range (0, int (len (transactions))):
print (str (transaction_counter) + transactions[element])
transaction_counter = transaction_counter + 1
``````

Actual output:

1. deposit \$ 200 in savings
2. deposit \$ 5 in the checking account
3. Transfer \$ 200 of checks to savings
4. \$ 20 withdrawal of savings
5. balance inquiry

Expected performance:
1. balance inquiry
2. \$ 20 savings withdrawal
3. Transfer \$ 200 from checking account to savings
4. deposit \$ 5 on the check
5. Deposit \$ 200 in savings

## python 3.x – Script does not apply changes to xlsx

I write because I am developing a script to screen repeated records in an excel with openpyxl. The script is as follows:

``````import openpyxl as xl

def main (file):
sh = wb.active
store = []
for and in range (1, 1 + sh.max_row):
store.append (sh["B" + str(e)].value)

many = []
for and in store:
if many.count (e) <1 < store.count(e):
many.append(e)

for e in range(1, 1 + sh.max_row):
count = 0
if many.count(sh["B" + str(e)].value) > 0 and count> 0:
sh["J" + str(e)].value = "N"
elif many.count (sh["B" + str(e)].value)> 0:
count + = 1

wb.save (file.replace (".xlsx", "_act.xlsx"))
``````

What it does is: take all the possible values ​​in column B, see which ones are repeated (that is, they are present more than once) and separate them (it does so in a separate list, hence the A <1 <B , since I want the count of the same in the separate list to be less than 1 and that the count in the list of records be greater than 1). Once you have the separate list, look at record to record in column B if it is present in the repeated list. If it is and is not the first instance of it, mark it in column J with an "N" to be able to separate it via excel later.

The fact is that, as I execute it, it returns a copy of the original (and I know it is a copy because I know that there are repeated records in column B.

## Python 3.x – Convert a string into a string of bytes

I want to convert a string into a string of bytes. The chain comes exactly in this form. Coding & # 39; сp1251 & # 39 ;. How to do it well?

str = & # 39; см³ & # 39;

bytes (str, & # 39; cp1251 & # 39;)

As a result, I get
UnicodeEncodeError: the codec & # 39; charmap & # 39; can not encode the character & # 39; xb3 & # 39; in position 2: the character is assigned to

## Python 3.x – The Uvicorn server shuts down unexpectedly

I am working with the FastAPI framework, served by the Uvicorn server.
My application should execute some numerical calculation that consumes a lot of time in a final point (/ execute). For this I am using & # 39; background_task & # 39; of fastAPI (which is basically & # 39; background_task & # 39; from Starlette).

When executing the application, after some moments of nominal behavior, the server shuts down for some reason.

The application records look like this:

``````INFO: server process started [922]
INFO: Waiting for the start of the application.
DEBUG: None - ASGI [1] Started
DEBUG: None - ASGI [1] Sent {& # 39; type & # 39 ;: & # 39; lifespan.startup & # 39;}
DEBUG: None - ASGI [1] Received {& # 39; type & # 39; lifespan.startup.complete & # 39;}
INFO: Uvicorn runs on http://0.0.0.0:8000 (Press CTRL + C to exit)
DEBUG: (& # 39; 10 .0.2.111 & # 39 ;, 57396) - Connected
DEBUG: (& # 39; 10 .0.2.111 & # 39 ;, 57397) - Connected
DEBUG: (& # 39; 10 .0.2.111 & # 39 ;, 57396) - ASGI [2] Started
DEBUG: (& # 39; 10 .0.2.111 & # 39 ;, 57396) - ASGI [2] Received {& # 39 ;: & # 39; http.response.start & # 39 ;, & # 39 ;: & # 39 ;: 200, & # 39; headlines & # 39 ;: & # 39;<...>& # 39;
INFO: (& # 39; 10 .0.2.111 & # 39 ;, 57396) - "GET / run HTTP / 1.1" 200
DEBUG: (& # 39; 10 .0.2.111 & # 39 ;, 57396) - ASGI [2] Received {& # 39; type & # 39 ;: & # 39; http.response.body & # 39 ;, & # 39; body & # 39 ;: & # 39;<32 bytes>& # 39;
DEBUG: (& # 39; 10 .0.2.111 & # 39 ;, 57396) - ASGI [3] Started
DEBUG: (& # 39; 10 .0.2.111 & # 39 ;, 57396) - ASGI [3] Received {& # 39 ;: & # 39; http.response.start & # 39 ;, & # 39 ;: & # 39 ;: 404, & # 39; headlines & # 39 ;: & # 39;<...>& # 39;
INFO: (& # 39; 10 .0.2.111 & # 39 ;, 57396) - "GET /favicon.ico HTTP / 1.1" 404
DEBUG: (& # 39; 10 .0.2.111 & # 39 ;, 57396) - ASGI [3] Received {& # 39; type & # 39 ;: & # 39; http.response.body & # 39 ;, & # 39; body & # 39 ;: & # 39;<22 bytes>& # 39;
DEBUG: (& # 39; 10 .0.2.111 & # 39 ;, 57396) - ASGI [3] Finished

...

DEBUG: (& # 39; 10 .0.2.111 & # 39 ;, 57396) - Offline
... The background task is complete.
DEBUG: (& # 39; 10 .0.2.111 & # 39 ;, 57396) - ASGI [2] Finished
DEBUG: (& # 39; 10 .0.2.111 & # 39 ;, 57397) - Offline
DEBUG: (& # 39; 10 .0.2.111 & # 39 ;, 57405) - Connected

...
The application continues, with requests and background tasks completed.
At some point, during the execution of a task in the background:

INFO: turning off
DEBUG: (& # 39; 10 .0.2.111 & # 39 ;, 57568) - Offline
DEBUG: (& # 39; 10 .0.2.111 & # 39 ;, 57567) - Offline
INFORMATION: Pending completion of tasks in the background. (CTRL + C to force the exit)
DEBUG: (& # 39; 10 .0.2.111 & # 39 ;, 57567) - ASGI [6] Finished
INFO: Waiting for the application to close.
DEBUG: None - ASGI [1] Sent {& # 39; type & # 39 ;: & # 39; lifespan.shutdown & # 39;}
DEBUG: None - ASGI [1] Received {& # 39 ;: & # 39; lifespan.shutdown.complete & # 39;}
DEBUG: None - ASGI [1] Finished
INFO: Process of the finished server [922]
``````

I really do not understand why this happens. I have no idea what to try to fix it.

My code looks like this.

``````#! / usr / bin / env python3.7
import time
import uvicorn
from starlette.responses import JSONResponse
import my_imports_from_project

analysis_api = FastAPI ()

@ analysis_api.get ("/")
Async def root ():
returns {"message": "root"}

@ analysis_api.get ("/ test")
async def test ():
returns {"message": "test"}

@ analysis_api.get ("/ run")
try:
some_checks (name)
except RaisedExceptions:
body = {"running": False,
"name name,
return JSONResponse (state_code = 400, content = body)
body = {"running": True,
"name name}
return JSONResponse (state_code = 200, content = body)

yes __name__ == "__main__":
uvicorn.run ("api: analysis_api", host = "0.0.0.0", log_level = "debug")

``````

## elliptic curve (y ^ 2 = x ^ 3 + 3x +8) (mod 13) – torsion groups

Corollary 6.4. Leave $$E$$ be an elliptical curve and leave $$m en mathbb {Z}$$ with $$m ne 0$$.

(b) yes $$m ne 0$$ in $$K$$, that is, if any $$operatorname {char} (K) = 0$$ or $$p: = operatorname {char} (K)> 0$$ Y $$p nmid m$$, so $$E[m] = mathbb {Z} / m mathbb {Z} times mathbb {Z} / m mathbb {Z}$$.

(page 86 of [Silverman, The Arithmetic of Elliptic Curves, 2nd Edition])

Leave $$E: y ^ 2 = x ^ 3 + 3x + 8$$ finished $$mathbb {Z} / 13 mathbb {Z}$$. I just calculated the points on this curve. exist $$# E[3] stackrel {?} {=} 2$$ order points $$3$$ Y $$# E[9] stackrel {?} {=} 6$$ Points of order 9.

(i) expected $$9$$ order points $$3$$, as $$# E[3] = # left ( mathbb {Z} / 3 mathbb {Z} times mathbb {Z} / 3 mathbb {Z} right) = 9$$. Because there is only $$2$$ order points $$3$$?

(ii) I calculated $$# E ( mathbb {Z} / 13 mathbb {Z}) = 9$$ (by brute force). So I understand the above Corollary 6.4, there must be some points of order $$5$$, as $$p = 13 nmid 5$$. But the existence of such a point $$P in E[5]$$ would imply the existence of some subgroup $$langle P rangle leq E ( mathbb {Z} / 13 mathbb {Z})$$ With order $$5$$ as well. This can not happen, since the order of a subgroup must divide the order of the upper group. As $$5 nmid 9$$, there can be no points of order $$5$$.

What am I missing?

## python 3.x – How do the loop runners (presumably synchronized) start the loop of asynchronous events?

Where is the implementation interface in Python documented that allows asynchronous loop brokers (trio, asyncio, curio) to start all the shebang?

We know that synchronization functions can not call asynchronous functions, and yet, asynchronous implementations have a magic function that starts the entire event loop, for example:

``````trio.run (some ... asynchronous ... fun) ...

docstring: except that: func: `run` can (and should) be called from a synchronous context.
``````

Google & # 39; python start an async event loop & # 39; it refers to asyncio documentation, which is a specific implementation.

Are the asyncio / trio / curio loop runners crafted to break the sync-> async wall?