I am newbie in Python and i require your help.I have a Mac and use python 3. Work with SublimeText and this is what i receive while running my code==> i received this error:NameError: name '__tablename__' is not defined
Thank you in advance!!!
My entire code is:
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:', echo=True)
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
#creare de tabela
from sqlalchemy import Column, Integer, String
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
program = Column(String)
aka = Column(String)
adresa = Column(String)
city = Column(String)
state = Column(String)
country = Column(String)
postalcode = Column(String)
def __repr__(self):
return "<User(name='%s', fullname='%s', program='%s', aka='%s',adresa='%s',city='%s',country='%s',postalcode='%s',)>" %(
self.name, self.fullname, self.program, self.aka, self.adresa, self.city, self.state, self.country,self.postalcode)
#creare de tabela
User.__tablename__
table('users', MetaData(bind=None),
Column('id', Integer(),table=(users), primary_key=True, nullable=False),
Column('name', String(), table=(users)),
Column('fullname', String(), table=(users)),
Column('program', String(), table=(users)),
Column('aka', String(), table=(users)),
Column('adresa', String(), table=(users)),
Column('city', String(), table=(users)),
Column('state', String(), table=(user)),
Column('country', String(), table=(users)),
Column('postalcode', String(), table=(users), schema=None))
Because it's a "private variable"
[...] Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped.
In your usecase, you can access it with User._user__tablename__
To avoid this problem, mark your varbaile with one leading underscore, and remove the two trailing underscores. This is suggestet by pep8:
_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.
Related
I am unable to declare a constructor in Python 3.8. I am not able to declare a constructor. The system is showing the error message:
"Undefined Variable" and "illegal target for annotations.
class Employee:
def__init__(self,name,id):
self.name = name
self.id = id
def dispaly(self):
print("ID: %d\nName: %s"%(self.id,self.name))
emp1 = Employee("Robert",101)
emp1.dispaly()
You are missing a space between def and __init__ keywords.
Correct way:
class Employee:
def __init__(self, name, id):
self.name = name
self.id = id
def display(self):
print("Employee Name is {} and ID is {}.".format(self.name, self.id))
emp1 = Employee("Robert", "E001")
emp1.display()
I'm reading through the Doobie documentation and trying to do a simple get or create within a transaction. I get an option off the first query and attempt to do a getOrElse and run an insert within the else, however I keep getting a value map is not a member of Any within the getOrElse call. What's the correct way to either get an existing or create a new row in instances and return that result in a transaction?
import doobie._
import doobie.implicits._
import cats._
import cats.effect._
import cats.implicits._
import org.joda.time.DateTime
import scala.concurrent.ExecutionContext
case class Instance(id : Int, hostname : String)
case class User(id : Int, instanceId: Int, username : String, email : String, created : DateTime)
class Database(dbUrl : String, dbUser: String, dbPass: String) {
implicit val cs = IO.contextShift(ExecutionContext.global)
val xa = Transactor.fromDriverManager[IO](
"org.postgresql.Driver", dbUrl, dbUser, dbPass
)
def getOrCreateInstance(hostname: String) = for {
existingInstance <- sql"SELECT id, hostname FROM instances i WHERE i.hostname = $hostname".query[Instance].option
ensuredInstance <- existingInstance.getOrElse(sql"INSERT INTO instances(hostname) VALUES(?)".update.withGeneratedKeys[Instance]("id", "hostname"))
} yield ensuredInstance
}
I got the following answer thanks to the people on the #scala/freenode chatroom. I'm posting it here for completeness and if people are interested in doing this without the for comprehension in the other answer.
def getOrCreateInstance(hostname: String): ConnectionIO[Instance] =
OptionT(sql"SELECT id, hostname FROM instances i WHERE i.hostname = $hostname".query[Instance].option)
.getOrElseF(sql"INSERT INTO instances(hostname) VALUES($hostname)".update.withGeneratedKeys[Instance]("id", "hostname").compile.lastOrError)
I believe something like this should work for you,
def getOrCreateInstance(hostname: String): ConnectionIO[Instance] = for {
existingInstance <- sql"SELECT id, hostname FROM instances i WHERE i.hostname = $hostname".query[Instance].option
ensuredInstance <- existingInstance.fold(sql"INSERT INTO instances(hostname) VALUES($hostname)".update.withGeneratedKeys[Instance]("id", "hostname").take(1).compile.lastOrError)(_.pure[ConnectionIO])
} yield ensuredInstance
where you are compiling the fs2 Stream and also lifting the existing instance into a ConnectionIO in the case that it does already exist.
In the Persistent chapter of the Yesod book, an example is given where this entity
{-# LANGUAGE QuasiQuotes, TypeFamilies, GeneralizedNewtypeDeriving, TemplateHaskell, OverloadedStrings, GADTs #-}
import Database.Persist
import Database.Persist.TH
import Database.Persist.Sqlite
import Control.Monad.IO.Class (liftIO)
mkPersist sqlSettings [persist|
Person
name String
age Int
deriving Show
|]
generates the code
{-# LANGUAGE TypeFamilies, GeneralizedNewtypeDeriving, OverloadedStrings, GADTs #-}
import Database.Persist
import Database.Persist.Store
import Database.Persist.Sqlite
import Database.Persist.GenericSql.Raw (SqlBackend)
import Database.Persist.EntityDef
import Control.Monad.IO.Class (liftIO)
import Control.Applicative
data Person = Person
{ personName :: String
, personAge :: Int
}
deriving (Show, Read, Eq)
type PersonId = Key Person
instance PersistEntity Person where
-- A Generalized Algebraic Datatype (GADT).
-- This gives us a type-safe approach to matching fields with
-- their datatypes.
data EntityField Person typ where
PersonId :: EntityField Person PersonId
PersonName :: EntityField Person String
PersonAge :: EntityField Person Int
type PersistEntityBackend Person = SqlBackend
toPersistFields (Person name age) =
[ SomePersistField name
, SomePersistField age
]
fromPersistValues [nameValue, ageValue] = Person
<$> fromPersistValue nameValue
<*> fromPersistValue ageValue
fromPersistValues _ = Left "Invalid fromPersistValues input"
-- Information on each field, used internally to generate SQL statements
persistFieldDef PersonId = FieldDef
(HaskellName "Id")
(DBName "id")
(FTTypeCon Nothing "PersonId")
[]
persistFieldDef PersonName = FieldDef
(HaskellName "name")
(DBName "name")
(FTTypeCon Nothing "String")
[]
persistFieldDef PersonAge = FieldDef
(HaskellName "age")
(DBName "age")
(FTTypeCon Nothing "Int")
[]
Why does adding deriving Show to the Person entity generate the derivation of all three typeclasses (Show, Read, Eq)? I'm very new to Haskell and Yesod, so I apologize if it's obvious, but I can't find the answer anywhere! Is it just an error in the documentation? Thanks!
Easy: it's a typo in the book :). If you look at the actual generated code (with -ddump-splices), you'll see that it's only actually deriving the Show instance.
In SQLAlchemy, I want to define a mixin that automatically creates an Index in inheriting tables.
Assuming that the inheriting table has a member list called 'keys', I want the mixin to create in the inheriting table a single multi-column Index over the columns listed in keys. However, the mixin doesn't know what the keys are until the table is created!
How would I do this?
Example:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy import MetaData, Column, Index, Integer
metadata = MetaData()
Base = declarative_base(metadata=metadata)
class MyMixin(object):
#declared_attr
def __table_args__(cls):
return (Index('test_idx_%s' % cls.__tablename__, *cls.INDEX),)
class MyModel(MyMixin, Base):
__tablename__ = 'atable'
INDEX = ('a', 'b',)
id = Column(Integer, primary_key=True)
a = Column(Integer)
b = Column(Integer)
c = Column(Integer)
if __name__ == '__main__':
from sqlalchemy import create_engine
engine = create_engine('sqlite:///', echo=True)
metadata.bind = engine
metadata.create_all()
Docs: Combining Table/Mapper Arguments from Multiple Mixins
How do I tell SQLAlchemy to automatically reflect basic Foreign Key references as references to other ORM objects and not integer fields?
In both SQLAlchemy and it's SqlSoup, table columns are reflected automatically and relations can be defined manually:
class User(Base):
__table__ = metadata.tables['users']
loan = relation(Loans)
...
You can define relationships on SqlSoup classes:
>>> db.users.relate('loans', db.loans)
Try this magic )
Works for simple FK relations, and without db schemes
from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import mapper, relation
engine = create_engine("sqlite://", echo=True)
engine.execute('''
create table foo (
id integer not null primary key,
x integer
)''')
engine.execute('''
create table bar (
id integer not null primary key,
foo_id integer,
FOREIGN KEY(foo_id) REFERENCES foo(id)
)''')
metadata = MetaData()
metadata.reflect(bind=engine)
MAPPERS = {
}
repr_name = lambda t: '%s%s' % (t[0].upper(), t[1:])
for table in metadata.tables:
cls = None
# 1. create class object
cls_name = repr_name(str(table))
exec("""class %s(object): pass""" % cls_name)
exec("""cls = %s""" % cls_name)
# 2. collect relations by FK
properties = {}
for c in metadata.tables[table].columns:
for fk in c.foreign_keys:
name = str(fk.column).split('.')[0]
properties.update({
name: relation(lambda: MAPPERS[repr_name(name)]),
})
# 3. map table to class object
mapper(cls, metadata.tables[table], properties=properties)
MAPPERS.update({cls_name: cls})
if __name__ == '__main__':
from sqlalchemy.orm import sessionmaker
print 'Mappers: '
for m in MAPPERS.values():
print m
session = sessionmaker(bind=engine)()
foo = Foo()
foo.x = 1
session.add(foo)
session.commit()
print session.query(Foo).all()
bar = Bar()
bar.foo = foo
session.add(bar)
session.commit()
print session.query(Bar).all()