def uploadpublication(request, form_class=PublicationUploadForm, template_name="publications/upload.html"): """ upload form for publications """ publication = Publication() publication.author = request.user publication_form = form_class() if request.method == "POST": if request.POST.get("action") == "upload": publication_form = form_class(request.user, request.POST, request.FILES, instance=publication) if publication_form.is_valid(): if not is_valid_format(request.FILES["file_name"].name, request.FILES["file_name"].content_type): request.user.message_set.create( message=u"Tipo de arquivo inválido (Somente arquivos PDF/CBR/CBZ ou Imagem: JPG/GIF/PNG) ou nome do arquivo muito longo" ) else: publication = publication_form.save(commit=False) publication.date_added = datetime.datetime.now() publication.status = 0 publication.nr_pages = 0 publication.save() request.user.message_set.create(message=_(u"Publicação feita com sucesso '%s'") % publication.title) return HttpResponseRedirect(reverse("publications", args=(publication.author,))) calc_age(request.user.get_profile()) return render_to_response( template_name, {"form": publication_form, "is_me": True, "other_user": request.user}, context_instance=RequestContext(request), )
def vue_publication_save(request): to_template = {} if request.user.is_authenticated: image = request.FILES.get('image') data = request.POST.get('data') data = json.loads(data) id = data.get('id', None) title = data.get('title') text = data.get('text') books = data.get('books', None) authors = data.get('authors', None) series = data.get('series', None) if id: # Сохраняет изменения publication = Publication.objects.get(pk=id, user=request.user) publication.title = title publication.preview_text = Truncator(strip_tags(text)).words(33) publication.detail_text = text publication.user = request.user publication.series_id = series publication.save() publication.book.set(books) publication.author.set(authors) publication.series.set(series) else: # Создает новую коллекцию publication = Publication(title=title, user=request.user, preview_text=Truncator( strip_tags(text)).words(33), detail_text=text) publication.save() if books: publication.book.set(books) if authors: publication.author.set(authors) if series: publication.series.set(series) if image: publication.image.save(image.name, image) to_template['image'] = publication.image.url to_template['id'] = publication.id return JsonResponse(to_template)
def add_association(acc, article, is_associated=False): """ Adding association between `Publication` and `Experiment` objects in the Django models which is used by curators to approve or reject linkage between an article and a study. :param acc: ArrayExpress accession. e.g. ``E-MTAB-xxxx`` :type acc: str :param article: Json object as collected from Europe BMC. :type article: dict :param is_associated: Flag indicating whether the publication is already associated with the study in the AE database or not :type is_associated: bool """ experiment = retrieve_study_by_acc(acc)[0] exp = Experiment.objects.filter( Q(accession=acc) | Q(title=experiment.title) | Q(description=experiment.description)).first() # print exp, exp_created if not exp: exp = Experiment(accession=acc, title=experiment.title, description=experiment.description) exp.save() pub = Publication.objects.filter( Q(pubmed=article.get('pmid', -1)) | Q(pmc_id=article.get('pmcid')) | Q(doi=article.get('doi', 'ANY THING ELSE')) | Q(title=article['title'])).first() if not pub: pub = Publication(pubmed=article.get('pmid', None), pmc_id=article.get('pmcid'), doi=article.get('doi', None), title=article['title'], whole_article=json.dumps(article)) pub.save() else: pub.whole_article = json.dumps(article) pub.save() ass, ass_created = Association.objects.get_or_create(experiment=exp, publication=pub) if ass_created: ass.is_associated = is_associated ass.save()
def get_publication(unique_name, pmid): #check if publication exist, if so return, if not create new try: result = get_esummary_pmid(pmid) tmp_date = datetime.strptime(result["result"][pmid]["sortpubdate"], '%Y/%m/%d %H:%M') publication = Publication(title=result["result"][pmid]["title"], volume=result["result"][pmid]["volume"], issue=result["result"][pmid]["issue"], publication_year=tmp_date.strftime('%Y-%m-%d'), pages=result["result"][pmid]["pages"], unique_name=pmid+'-'+result["result"][pmid]["title"], publisher=result["result"][pmid]["fulljournalname"]) publication.validate_unique() publication.save() db = Db.objects.get(name='Pubmed') dbxref = Dbxref(accession=pmid, version='1', db=db) dbxref.validate_unique() dbxref.save() publication_dbxref = PublicationDbxref(publication=publication, dbxref=dbxref) publication_dbxref.validate_unique() publication_dbxref.save() rank = 1 tmp_list = result["result"][pmid]["authors"] for tmp in tmp_list: author = get_author(tmp["name"]) publication_author = PublicationAuthor(rank=rank, publication=publication, author=author) publication_author.validate_unique() publication_author.save() rank+=1 except ValidationError as e: publication = Publication.objects.get(unique_name=pmid+'-'+result["result"][pmid]["title"]) return publication
def add_publications(self, number): if number > 0: random = Random() users = User.objects.all() charts = string.lowercase + " " if len(users) > 0: for i in range(number): content = "".join([random.choice(charts) for a in range(random.randint(40, 100))]) publication_title = "".join( [random.choice(string.lowercase) for a in range(random.randint(15, 30))]).title() author = random.choice(users) publication_type = random.choice(publication_types) publication = Publication(author=author, title=publication_title, content=content, publication_type=publication_type) publication.save() self.stdout.write("%i publications was added to database" % number) else: self.stdout.write("No user to add publication") else: self.stdout.write("Invalid number of publications to add was set. Nothing done")
def mutate_and_get_payload(cls, root, info, **input): # проверяет токен token = input.get('token', None) if token != '******************': return "Invalid token" publication = Publication( title=input.get('title'), preview_text=input.get('preview_text', ''), detail_text=input.get('detail_text', ''), image=input.get('image', ''), rating=input.get('rating', 0), user_id=input.get('user_id', 5227), date_create=input.get('date_create'), show_counter=input.get('show_counter'), ) if input.get('pk'): publication.pk = input.get('pk') if input.get('age'): publication.age = input.get('age', 0) publication.save() if input.get('author'): publication.author.set(input.get('author')) publication.save() if input.get('book'): try: publication.book.set(input.get('book')) publication.save() except Exception as e: pass return AddPublication(publication=publication)
volume = int(volume.split('(')[0]) if not volume: volume = None year = pub['year'] if not year: year = None # tukšo string aizstājam ar none publication = Publication( type_id=2, title=bibtex, # excelī tajā vietā bija raksta nosaukums authors=pub.get('authors'), year=year, journal=pub['journal'], publisher=pub['publisher'], volume=volume, external=False) publication.save() for author in publication.authors_list: person = findPerson(author.strip()) if person: person.publications.add(publication) # --- beigas tam, ja jāveido publikācija pašam jo nav bibtex if pub['indexed']: publication.indexed = pub['indexed'] publication.save() if pub['project_name']: for name in pub['project_name'].split(';'): for project in Project.objects.all(): if project.title == name.strip(): project.publications.add(publication)
def load_pmids(pmids, force_update=False): """ Loads publications into the database from a list of PubMed IDs passed as integers into the database when they do not already exist. """ pmids = list(set([int(x) for x in pmids])) logger.debug('Starting to load PMID(S) %s', pmids) if not force_update: logger.info('Checking %s PMIDS', len(pmids)) existing_pubs = set(Publication.objects.filter(pmid__in=pmids).values_list('pmid', flat=True)) pmids = set(pmids) pmids.difference_update(existing_pubs) logger.info('About to fetch %s new PMIDs.', len(pmids), extra={'data':{'pmids': pmids}}) if not pmids: logger.debug('pmids are none') return None pmids_mia = [str(x) for x in pmids] for i in xrange(len(pmids_mia) / 5000 + 1): #Efetch Maximum, Batch 5000 per request query_list = pmids_mia[i * 5000:(i + 1) * 5000] query_str = ','.join(query_list) qdict = settings.ETOOLS_CONFIG['query_params'] qdict['id'] = query_str # Have to use post if data being sent is > 200 r = requests.post(settings.ETOOLS_CONFIG['base_url'], data=qdict) error_cnt = 0 while r.status_code != 200 and error_cnt < NUM_PUBMED_RETRIES: error_cnt += 1 time.sleep(0.5) r = requests.post(settings.ETOOLS_CONFIG['base_url'], data=qdict) if r.status_code != 200: logger.warning('Requests to the PubMed server with data %s failed ' 'after %s attempts.', qdict, NUM_PUBMED_RETRIES + 1) pub_page = r.text if pub_page: logger.debug('Request to pubmed server returned pub_page') xmltree = ET.fromstring(pub_page.encode('utf-8')) pubs = xmltree.findall('.//DocumentSummary') # pub_dicts will be a list of publications, where each # of them is a dictionary pub_dicts = map(parse_pub, pubs) for index, pub in enumerate(pub_dicts): logger.debug('Making new pub %s', pub) if pub is not None: new_pub = None if force_update: try: new_pub = Publication.objects.get(pmid=pub['pmid']) except Publication.DoesNotExist: new_pub = Publication() new_pub.pmid = pub['pmid'] new_pub.title = pub['title'] new_pub.authors = pub['authors'] new_pub.date = pub['date'] new_pub.journal = pub['journal'] new_pub.volume = pub['volume'] new_pub.pages = pub['pages'] new_pub.issue = pub['issue'] else: new_pub = Publication(**pub) if not new_pub.issue: logger.info('no issue for %s', new_pub.pmid) if not new_pub.volume: logger.info('no volume for %s', new_pub.pmid) if not new_pub.pages: logger.info('no pages for %s', new_pub.pmid) new_pub.save() logger.debug('Finished saving pub %s', new_pub) else: bad_pmid = pubs[index].get('uid') logger.warning('PMID %s has no publication in pub_page %s', bad_pmid, pub_page) else: logger.warning('There was no page returned from pubmed server!!')