How to pass variable from views to model in Django - python-3.x

Models.py
from django.db import models
class Voiceapi(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=200)
voice_text = models.CharField(max_length=200,default="voice_data")
Views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from rest_framework import viewsets
import requests
import gdown
from pydub import AudioSegment
import speech_recognition as sr
from .serializers import *
from .models import *
import time
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from urllib.request import urlopen
# create a viewset
class VoiceViewSet(viewsets.ModelViewSet):
# define queryset
queryset = Voiceapi.objects.all()
# specify serializer to be used
serializer_class = VoiceSerializer
#
print(Voiceapi.objects.values())
datas = Voiceapi.objects.values()
print(datas)
for i in datas:
try:
print("Audio File-->",i['name'])
audio_url = i['name']
audio_id = i['id']
def VoiceRecognizer(audio,audio_id):
r = sr.Recognizer()
with sr.AudioFile(audio) as source:
audio_text = r.listen(source)
try:
text = r.recognize_google(audio_text)
print(text)
Voiceapi.objects.filter(pk=audio_id).update(voice_text=text)
except:
print('Audio Not Clear')
audio = "/home/venpep/voicetotext/messages/media/test.wav"
VoiceRecognizer(audio,audio_id)
except:
print("Not audio file")
I need to pass the variable "text" from my view.py to models.py to set the default in voice_text.Is there any solution to get the text from the view page. The text variable is a basic string that needs to pass to the models.py

as I understood from your comment, you can override the save method in django model and put your logic, in this way you can edit field value before save it and send it in response
class Voiceapi(models.Model):
...
def save(self, *args, **kwargs):
...

Related

Scalable factory pattern with Flask, Pytest using SqlAlchemy

Goal:
I want a scalable way to add factories that represent my models so I can manipulate them at run time and have a test DB from test set up to tear down.
Issue:
cls = <class 'tests.factories.analysis.Analysis'>
model_class = <class 'src.api.someModel'>, session = <function dbsession at 0xffffb8e6a5e0>, args = ()
kwargs = {'analysis_id': 365, 'created_by': 619, 'file_extension': 'Stop.', 'original_file_name': 'Share.', ...}
#classmethod
def _save(cls, model_class, session, args, kwargs):
session_persistence = cls._meta.sqlalchemy_session_persistence
obj = model_class(*args, **kwargs)
> session.add(obj)
E AttributeError: 'function' object has no attribute 'add'
What this means to me ^ my Session object is not behaving the way it should, why i dont know.
conftest.py ( got this code snippet from here https://gist.github.com/kissgyorgy/e2365f25a213de44b9a2?permalink_comment_id=3496042 )
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from domain.declarative import Base
from sqlalchemy.orm import sessionmaker
TEST_DATABASE = "postgresql://postgres:postgres#localhost:5432/testDB"
#pytest.fixture(scope="session")
def engine():
return create_engine(TEST_DATABASE)
#pytest.fixture(scope="session")
def tables(engine):
Base.metadata.create_all(engine)
yield
Base.metadata.drop_all(engine)
#pytest.fixture
def dbsession(engine, tables):
"""Returns an sqlalchemy session, and after the test tears down everything properly."""
connection = engine.connect()
# begin the nested transaction
transaction = connection.begin()
# use the connection with the already started transaction
session = Session(bind=connection)
yield session
session.close()
# roll back the broader transaction
transaction.rollback()
# release connection
connection.close()
Base_factory.py
import factory.alchemy
from sqlalchemy.orm import scoped_session, sessionmaker
from the.code.above import engine, dbsession
session = scoped_session(sessionmaker(bind=engine))
class BaseFactory(factory.alchemy.SQLAlchemyModelFactory):
class Meta:
abstract = True
sqlalchemy_session = dbsession
sqlalchemy_session_persistence = "commit"
Child Factory
import random
from datetime import datetime
from faker import Faker
from domain.declarative import TheModel
from tests.factories.base_factory import BaseFactory
faker = Faker()
class ChildFactory(BaseFactory):
class Meta:
model = TheModel
analysis_id = random.randrange(1, 1000)
created_by = random.randrange(1, 1000)
file_extension = faker.text(max_nb_chars=10)
original_file_name = faker.text(max_nb_chars=10)
upload_date = faker.date_between_dates(
date_start=datetime(2000, 1, 1), date_end=datetime(2019, 12, 31)
)
some test
class TestSimple(unittest.TestCase):
def test_important_stuff(self):
f = ChildFactory()
So this looks like to me the Session object is not being instantiated properly and is of a type function? it's calling add here at somepoint and we get an atrribute error because of that where am I going wrong?
session.add(obj)
E AttributeError: 'function' object has no attribute 'add'

How to use proxy in scrapy crawler?

from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from scraper_api import ScraperAPIClient
class Spider(CrawlSpider):
allowed_domains = ['example.com']
client = ScraperAPIClient('xyz')
#Initilize method for taking argument from user
def __init__(self, category=None,location=None ,**kwargs):
#self.start_urls = [client.scrapyGet(url = 'http://example.com')]
super().__init__(**kwargs) # python3
rules = (
Rule(LinkExtractor(restrict_xpaths="//div[contains(#class,'on-click-container')]/a[contains(#href, '/biz/')]"), callback='parse_item', follow=True,process_request='set_proxy'),
#for next page
Rule(LinkExtractor(restrict_xpaths='//a[contains(#class,"next-link")]'),process_request='set_proxy')
)
def set_proxy(self,request):
pass
def parse_item(self, response):
# contains data
yield{
# BUSINESS INFORMATION
"Company Name": response.xpath('//title').extract_first(),
}
Here I don't understand how to write set_proxy function that send request to scraper API server. Please help about this.

how to import class object in python from another file

Suppose I have a directory with files classfile.py and a test_classfile.py
here's classfile.py
class Student:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
return (self.firstname + self.lastname)
if __name__ == '__main__':
s = Student('John', 'Doe')
What I'd like to do is import just the object s
into the test_file.py
something like this,
from dir.classfile.Student import s
def test_classfile():
assert str(s.printname()).isalpha()
I get the following error
ModuleNotFoundError: No module named 'dir.classfile.Student'; 'dir.classfile' is not a package
As it is said 'dir.classfile' is not a package. If your .py files are both in the same directory, you just do 'import classfile'. Suppose the classfile.py was in the different directory, you would have to do the following:
import os.path
path_to_mods = os.path.abspath('path/to/classfile')
sys.path.insert(0, path_to_mods)
import classfile
You cannot import from 'Student' - this is an object. But you can import Student like this:
from classfile import Student
Also you cannot import instance of the class which is s. You should import the object like it it said above and then create an instance of it.

Why I can't call the object's class member in this case?

This code runs at the beginning
from Controller.DiscordClient import DiscordClient
if __name__ == '__main__':
try:
DiscordClient.getInstance().run(DiscordClient.TOKEN)
except Exception as ex:
print(ex)
I have this DiscordClient class:
import discord
from Controller.Startup_Manager import *
from Controller.Message_Manager import *
from Controller.User_Message_Handler import *
from Controller.ReactionHandler import *
class DiscordClient(discord.Client):
TOKEN = "token"
__instance = None
#staticmethod
def getInstance():
""" Static access method. """
if DiscordClient.__instance is None:
DiscordClient()
return DiscordClient.__instance
def __init__(self):
super().__init__()
Startup_Manager.initiate_startup()
""" Virtually private constructor. """
if DiscordClient.__instance is not None:
raise Exception("This class is a singleton!")
else:
DiscordClient.__instance = self
And the second class:
from .DiscordClient import DiscordClient
from Controller.POTD import *
from Controller.Task_Manager import *
from Model.RegexParseConstants import *
import re
class Startup_Manager:
__TOO_MANY_REQUESTS_WAIT = 3 * 60
__WAIT_TIME_UPDATE_VERSION_SECS = 45 * 60
#staticmethod
def initiate_startup():
print(DiscordClient.TOKEN)
When I run this code and initiate_startup() gets called, it crashes, gives me this error:
name 'DiscordClient' is not defined
Edit: An update to the whole scenario. I don't know why the code crashes at DiscordClient despite this which called Startup_Manager in the first place.
I suspect you have a Controller.py file in which you have the DiscordClient. so your import statement should be from Controller import * or specifically from Controller import DiscordClient
The problem was in the circular import, as suggested by #syfluqs. Delaying it to the last moment was the quick solution according to this post:
https://stackoverflow.com/a/50595843/

Unable to update newly linked issue - Jira/Scriptrunner - Epic/Issues In Epic

I have a piece of code. I am able to view all the values, but when it comes to updating the newly linked issue's Tempo "Account" field, nothing happens. I am using Scriptrunner For Jira's custom listener
I would expect the newly linked issue (issueInEpic) to have it's Tempo "Account" field (linkedField) value (oldCfValue) updated with the value (newCfValue) of the Epic's "Account" field value.
log.info() shows all of the values properly. The only issue is updating the linked issue.
import com.atlassian.jira.event.issue.link.IssueLinkDeletedEvent
import org.apache.log4j.Logger
import org.apache.log4j.Level
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.issue.ModifiedValue
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder
import com.atlassian.jira.issue.index.IssueIndexingService
import com.atlassian.jira.util.ImportUtils
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.event.type.EventDispatchOption
import com.atlassian.jira.issue.util.IssueChangeHolder
def log = Logger.getLogger(com.atlassian.jira.event.issue.link.IssueLinkCreatedEvent)
log.setLevel(Level.INFO)
if ([IssueLinkCreatedEvent].contains(event.getClass())) {
if (event.issueLink.issueLinkType.name == "Epic-Story Link") {
def currentUser = ComponentAccessor.jiraAuthenticationContext.loggedInUser
def issueManager = ComponentAccessor.getIssueManager()
def cfManager = ComponentAccessor.getCustomFieldManager()
def accountField = cfManager.getCustomFieldObjects(event.issueLink.sourceObject)?.find{it.name == "Account"}
def linkedField = cfManager.getCustomFieldObjects(event.issueLink.destinationObject)?.find{it.name == "Account"}
MutableIssue issueInEpic = event.issueLink.destinationObject as MutableIssue
MutableIssue epic = event.issueLink.sourceObject as MutableIssue
def newCfValue = accountField.getValue(epic)
def oldCfValue = linkedField.getValue(issueInEpic)
issueInEpic.setCustomFieldValue(linkedField, newCfValue)
issueManager.updateIssue(currentUser, issueInEpic, EventDispatchOption.DO_NOT_DISPATCH, false)
def issueIndexingService = ComponentAccessor.getComponent(IssueIndexingService.class)
def wasIndexing = ImportUtils.isIndexIssues()
ImportUtils.setIndexIssues(true)
issueIndexingService.reIndex(event.issueLink.destinationObject)
ImportUtils.setIndexIssues(wasIndexing)
log.info(accountField)
log.info(newCfValue)
log.info(oldCfValue)
log.info(issueInEpic)
log.info(epic)
log.info(linkedField)
}
}

Resources