" __conform__() is not a valid Streamlit command." - sqlite

While I was running my code in pycharm, it is showing:
__conform__() is not a valid Streamlit command."
I am trying to store input and result in my streamlit app in sqlite3 database and and display it in tabular format in same streamlit app.
Main code page:home_task.py:
import streamlit as st
from homework_db import create_table, add_data
def main():
st.title("Streamlit Exercise")
menu = ['Insert', 'Read']
choice = st.sidebar.selectbox("Menu", menu)
create_table()
if choice == 'Insert':
st.subheader('Lets check Sentiment')
line = st.text_area("Enter the sentence")
result = st.text("Positive")
if st.button("Add Task"):
add_data(line, result)
st.success("Successfully added data in database")
elif choice == 'Read':
st.subheader('Datatable')
if __name__ == "__main__":
main()
The other file: homework_db.py:
import sqlite3
conn = sqlite3.connect("homework2_db", check_same_thread=False)
c = conn.cursor()
## database-table-field-datatype##
def create_table():
c.execute('CREATE TABLE IF NOT EXISTS database(sentence TEXT, sentiment TEXT)')
def add_data(line, result):
c.execute('INSERT INTO database(sentence,sentiment) VALUES(?,?)', (line, result))
conn.commit()
Everything seems fine, I have followed many youtube videos for sql query, it seems right but I am not sure why streamlit is not accepting the code.
I also checked python docs, (https://docs.python.org/3.6/library/sqlite3.html#letting-your-object-adapt-itself) but could not figure out how this is related to my problem.

It's because result is not a string but a Streamlit object:
>>> import streamlit
>>> result = st.text("Positive")
>>> type(result)
<class 'streamlit.delta_generator.DeltaGenerator'>
What you need is to do is remove the st.text():
if choice == 'Insert':
st.subheader('Lets check Sentiment')
line = st.text_area("Enter the sentence")
result = "Positive" # no st.text()
if st.button("Add Task"):
add_data(line, result)
st.success("Successfully added data in database")

Related

Qt Designer/PyQt/Python how to access an element?

Please help. There is a layout ui file. I connected it - I did several manipulations through the Form class. Now I want to create a class with layout change. But I don’t understand how to “reach out” to the element .... I am attaching the code, the ui file too
Converting to py file does not make sense in my case. I ask for help - tell me how can I create a class with what I have and change the elements?
File ui
https://github.com/Anzhelika007/PyQt6_app/blob/master/interface.ui
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow
import sqlite3
Form, Window = uic.loadUiType('interface.ui')
app = QApplication([sys.argv])
window = Window()
form = Form()
form.setupUi(window)
window.show()
# so it works, but I want to understand - how can I create a class correctly
# form.label_11.setText('erthtzrjnsymzgs')
class UI(QMainWindow, Form):
def __init__(self):
super(UI, Form, self).__init__()
self.setupUi(self)
self.label_11.setText('erthtzrjnsymzgs') # this does not work
self.tableWidget.setColumnWidth(0, 50) # this does not work
self.tableWidget.setColumnWidth(1, 100) # this does not work
self.tableWidget.setColumnWidth(2, 150) # this does not work
self.tableWidget.setColumnWidth(3, 200) # this does not work
def registration():
user_login = form.userName.text()
user_email = form.email.text()
user_phone = form.phoneNamber.text()
user_value = (user_login, user_email, user_phone)
try:
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
cursor.execute("INSERT INTO users(Username, Email, PhoneNumber) VALUES (?,?,?)", user_value)
conn.commit()
cursor.execute("SELECT * FROM users")
k = cursor.fetchall()
print(k)
cursor.close()
except Exception as e:
print(e)
print(user_value)
form.addUserBtn.clicked.connect(registration)
sys.exit(app.exec())
# database creation code I have separately
import sqlite3
with sqlite3.connect('database.db') as db:
cursor = db.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS users(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
Username VARCHAR(30),
Email VARCHAR(30),
PhoneNumber VARCHAR(15)
)""")
users_x = [('Yanitya', 'geffelleceffe-7860#yopmail.com', '9(3484)364-32-92'),
('Ricahav', 'kajaddunneito-2898#yopmail.com', '5(4119)578-75-50'),
('Corbert', 'tebrijofuyu-9922#yopmail.com', '4(04)160-64-89'),
('Xerxesar', 'houcrukefamu-5882#yopmail.com', '152(238)276-36-46')]
cursor.executemany("INSERT INTO users(Username, Email, PhoneNumber) VALUES (?,?,?)", users_x)
for i in cursor.execute('SELECT * FROM users'):
print(i)

Moto doesn't mock the db properly

What am I doing wrong here?
This is my first time using moto and I'm really confused
conftest.py:
#pytest.fixture(scope='module')
def dynamodb(aws_credentials):
with mock_dynamodb2():
yield boto3.resource('dynamodb', region_name='us-east-1')
#pytest.fixture(scope='module')
def dynamodb_table(dynamodb):
"""Create a DynamoDB surveys table fixture."""
table = dynamodb.create_table(
TableName='MAIN_TABLE',
KeySchema=[
[..]
table.meta.client.get_waiter('table_exists').wait(TableName='MAIN_TABLE')
yield
testfile:
mport json
import boto3
from moto import mock_dynamodb2
#mock_dynamodb2
def test_lambda_handler(get_assets_event, dynamodb, dynamodb_table):
from [...] import lambda_handler
dynamodb = boto3.client('dynamodb')
response = lambda_handler(get_assets_event, "")
data = json.loads(response["body"])
assert response["statusCode"] == 200
assert "message" in response["body"]
assert data["message"] == "hello world"
# assert "location" in data.dict_keys()
But the issue is my lambda is using a helper, which has a dynamodb helper under the hood and that dbhelper starts like this:
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(os.environ.get('MAIN_TABLE'))
def read_item(key: Dict):
try:
return table.get_item(Key=key)
except ClientError as e:
logging.exception(e)
raise exceptions.DatabaseReadException(f"Error reading from db: {key}") from e
Is that even possible to mock like this?
I feel like when I import the lambda handler it tries to overwrite my mocked db, but can't because obviously there's no os environ variable with the table name.

I am using jupyter to edit, but after import pymongo , why can't list the data I stored in MongoDB?

I am just the beginner of python, so sorry about this basic problem
enter image description here
import pymongo
client = pymongo.MongoClient('localhost', 27017)
ceshi = client['ceshi']
item_info = ['item_info3']
for i in item_info:
if i.find('area'):
print(i)
I am using Jupiter to edit, but after import pymongo , I can't list the data I stored in MongoDB. What could be the reason?
from bs4 import BeautifulSoup
import requests
import time
import pymongo
client = pymongo.MongoClient('localhost',27017)
ceshi = client['ceshi']
url_list = ceshi['url_list3']
item_info = ceshi['item_info3']
def get_links_from(channel,pages,who_sells=0):
#http://bj.58.com/diannao/0/pn2/
list_view = '{}{}/pn{}/'.format(channel,str(who_sells),str(pages))
wb_date = requests.get(list_view)
time.sleep(1)
soup = BeautifulSoup(wb_date.text,'lxml')
links = soup.select('tr.zzinfo > td.t > a.t')
if soup.find('td','t'):
for link in links:
item_link = link.get('href').split('?')[0]
else:
pass
url_list.insert_one({'url':item_link})
print(url_list)
def get_item_info(url):
wb_data = requests.get(url)
soup = BeautifulSoup(wb_data.text,'lxml')
no_longer_exist = '404' in
soup.find('script',type="text/javascript").get('src').split('/')
if no_longer_exist:
pass
else:
title = soup.title.text
price = soup.select('span.price.c_f50')[0].text
date = soup.select('li.time')[0].text
area = list(soup.select('spam.c_25d a')[0].stripped_strings) if
soup.find_all('c_25d') else None
item_info.insert_one({'title':title,'price':price,'date':date,'area':area})
print(item_info)
#print({'title':title,'price':price,'date':date,'area':area})
get_item_info('http://bj.58.com/pingbandiannao/25347275157966x.shtml')
#get_links_from('http://bj.58.com/yunfuyongpin/',2)
It looks like you are looping through an array of strings and trying to call find on a string:
item_info = ['item_info3']
for i in item_info:
if i.find('area')
If item_info3 is the name of your mongo collection in the ceshi database then you should do something like:
item_info = ceshi['item_info3']
Even then, I don't believe your find query is correct. It should be something like this:
for i in item_info.find():
print(i)
More information on Mongo/python:
https://docs.mongodb.org/getting-started/python/query/

Python - BaseHTTPServer , issue with POST and GET

I am making a very simple application with 2 webpages at the moment under URLs: localhost:8080/restaurants/ and localhost:8080/restaurants/new.
I have a sqlite database which i manipulate with SQLAlchemy in my python code.
On my first page localhost:8080/restaurants/, this just contains the lists of restaurants available in my database.
My second page localhost:8080/restaurants/new, is where i have a form in order to a new restaurant such that it displays on localhost:8080/restaurants.
However Whenever i enter a new restaurant name on form at localhost:8080/restaurants/new, it fails to redirect me back to localhost:8080/restaurants/ in order to show me the new restaurant, instead it just remains on the same url link localhost:8080/restaurants/new with the message "No data received" .
Below is my code:
import cgi
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
#import libraries and modules
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem
#create and connect to database
engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind=engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
class webServerHandler(BaseHTTPRequestHandler):
""" class defined in the main method"""
def do_GET(self):
try:
#look for url then ends with '/hello'
if self.path.endswith("/restaurants"):
self.send_response(200)
#indicate reply in form of html to the client
self.send_header('Content-type', 'text/html')
#indicates end of https headers in the response
self.end_headers()
#obtain all restaurant names from databse
restaurants = session.query(Restaurant).all()
output = ""
output += "<html><body><a href='/restaurants/new'>Add A New Restaurant</a>"
output += "</br></br>"
for restaurant in restaurants:
output += restaurant.name
output += """<div>
<a href='#'>Edit</a>
<a href='#'>Delete</a>
</div>"""
output += "</br></br>"
output += "</body></html>"
self.wfile.write(output)
print output
return
if self.path.endswith("/restaurants/new"):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
output = ""
output += "<html><body>"
output += "<h1>Add New Restaurant</h1>"
output += "<form method='POST' enctype='multipart/form-data action='/restaurants/new'>"
output += "<input name='newRestaurant' type='text' placeholder='New Restaurant Name'>"
output += "<input name='Create' type='submit' label='Create'>"
output += "</form></body></html>"
self.wfile.write(output)
return
except IOError:
self.send_error(404, "File %s not found" % self.path)
def do_POST(self):
try:
if self.path.endswith("/restaurants/new"):
ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
#check of content-type is form
if ctype == 'mulitpart/form-data':
#collect all fields from form, fields is a dictionary
fields = cgi.parse_multipart(self.rfile, pdict)
#extract the name of the restaurant from the form
messagecontent = fields.get('newRestaurant')
#create the new object
newRestaurantName = Restaurant(name = messagecontent[0])
session.add(newRestaurantName)
session.commit()
self.send_response(301)
self.send_header('Content-type', 'text/html')
self.send_header('Location','/restaurants')
self.end_headers()
except:
pass
def main():
"""An instance of HTTPServer is created in the main method
HTTPServer is built off of a TCP server indicating the
transmission protocol
"""
try:
port = 8080
#server address is tuple & contains host and port number
#host is an empty string in this case
server = HTTPServer(('', port), webServerHandler)
print "Web server running on port %s" % port
#keep server continually listening until interrupt occurs
server.serve_forever()
except KeyboardInterrupt:
print "^C entered, stopping web server...."
#shut down server
server.socket.close()
#run main method
if __name__ == '__main__':
main()
for reference here is my database_setup file where i create the database:
import sys
#importing classes from sqlalchemy module
from sqlalchemy import Column, ForeignKey, Integer, String
#delcaritive_base , used in the configuration
# and class code, used when writing mapper
from sqlalchemy.ext.declarative import declarative_base
#relationship in order to create foreign key relationship
#used when writing the mapper
from sqlalchemy.orm import relationship
#create_engine to used in the configuration code at the
#end of the file
from sqlalchemy import create_engine
#this object will help set up when writing the class code
Base = declarative_base()
class Restaurant(Base):
"""
class Restaurant corresponds to restaurant table
in the database to be created.
table representation for restaurant which
is in the database
"""
__tablename__ = 'restaurant'
#column definitions for the restaurant table
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
class MenuItem(Base):
"""
class MenuItem corresponds to restaurant table
table representation for menu_item which
is in the database
"""
__tablename__ = 'menu_item'
#column definitions for the restaurant table
name = Column(String(80), nullable=False)
id = Column(Integer, primary_key=True)
course = Column(String(250))
description = Column(String(250))
price = Column(String(8))
restaurant_id = Column(Integer, ForeignKey('restaurant.id'))
restaurant = relationship(Restaurant)
#create an instance of create_engine class
#and point to the database to be used
engine = create_engine(
'sqlite:///restaurantmenu.db')
#that will soon be added into the database. makes
#the engine
Base.metadata.create_all(engine)
I can't figure out why i cannot add new restuarants
I know this was a long time ago, but I figured out your problem.
First, the enctype='multipart/form-data' in your do_GET function under the if self.path.endswith("/restaurants/new"): portion is missing a final single quote. Second, you misspelt 'multipart' in if ctype == 'multipart/form-data':. Hope that can help you or others.
As shteeven said, the problem was with the encryption type in the form.
As the quote was missed, the 'Content-type' changed to 'application/x-www-form-urlencoded' so in that case you should parse it different as it's a string.
In order to manage both enctype you can modify your do_POST as the following
def do_POST(self):
try:
if self.path.endswith("/restaurants/new"):
ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
print ctype
#check of content-type is form
if (ctype == 'multipart/form-data') or (ctype == 'application/x-www-form-urlencoded'):
#collect all fields from form, fields is a dictionary
if ctype == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, pdict)
else:
content_length = self.headers.getheaders('Content-length')
length = int(content_length[0])
body = self.rfile.read(length)
fields = urlparse.parse_qs(body)
#extract the name of the restaurant from the form
messagecontent = fields.get('newRestaurant')
#create the new object
newRestaurantName = Restaurant(name = messagecontent[0])
session.add(newRestaurantName)
session.commit()
self.send_response(301)
self.send_header('Location','/restaurants')
self.end_headers()
return
Hope this extra information is useful for you!

Django page & category names showing as objects

This code is showing page and category names as objects and not by their respective title. Its supposed to show the names and its showing page objects and category objects instead for all the titles
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
import django
django.setup()
from rango.models import Category, Page
def populate():
python_cat = add_cat('Python')
add_page(cat=python_cat,
title="Official Python Tutorial",
url="http://docs.python.org/2/tutorial/")
add_page(cat=python_cat,
title="How to Think like a Computer Scientist",
url="http://www.greenteapress.com/thinkpython/")
add_page(cat=python_cat,
title="Learn Python in 10 Minutes",
url="http://www.korokithakis.net/tutorials/python/")
django_cat = add_cat("Django")
add_page(cat=django_cat,
title="Official Django Tutorial",
url="https://docs.djangoproject.com/en/1.5/intro/tutorial01/")
add_page(cat=django_cat,
title="Django Rocks",
url="http://www.djangorocks.com/")
add_page(cat=django_cat,
title="How to Tango with Django",
url="http://www.tangowithdjango.com/")
frame_cat = add_cat("Other Frameworks")
add_page(cat=frame_cat,
title="Bottle",
url="http://bottlepy.org/docs/dev/")
add_page(cat=frame_cat,
title="Flask",
url="http://flask.pocoo.org")
# Print out what we have added to the user.
for c in Category.objects.all():
for p in Page.objects.filter(category=c):
print ("- {0} - {1}".format(str(c), str(p)))
def add_page(cat, title, url, views=0):
p = Page.objects.get_or_create(category=cat, title=title, url=url, views=views)[0]
return p
def add_cat(name):
c = Category.objects.get_or_create(name=name)[0]
return c
# Start execution here!
if __name__ == '__main__':
print ("Starting Rango population script...")
populate()
What is wrong with the code or is the fault is with another file ? Using python 3.4 and django 1.7. Have I missed a file ? is there an other file I should share?
I had the same problem while studying through django with tango. I missed the method in the rango/modules.py in the class Page.
def str(self): # For Python 2, use unicode too
return self.title
__unicode__(self) seems to be creating the problem for Python-3 . Replace that with __str__(self) and it should work.
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
def __str__(self):
return self.name
class Page(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length = 128)
url = models.URLField()
views = models.IntegerField(default=0)
def __str__(self):
return self.title

Resources