[IOS] I made a widget that displays Qiita trends in Pythonista3. [Python]

Introduction

iPhone and iPad users, do you know an app called Pythonista3 that allows you to develop with Python on iOS devices? If you just want to run Python, I personally recommend Carnets --Jupyter. With Pythonista3, you can also develop functions that can be used from outside Abri, such as various shortcuts and widgets, and create games.

This time using such Pythonista 3 ** A widget that displays Qiita trends and opens the page in Safari when clicked ** I have created, so I would like to introduce it. qwid.png

What i did

In the case of this widget, the contents of Launcher.py under ʻExample / Widget` can be used almost as it is, so based on that,

・ Ability to get trend titles and URLs from the top page of Qiita ・ A function to temporarily save the acquired information ・ A function to access Qiita again and update the information if a certain amount of time has passed since the previous acquisition of information

Added.

code

The number of columns, the number of rows in the folded state, and the font size variables are summarized after the import statement, so you can adjust the layout to your liking. It will be cramped and hard to push, but if you set the number of lines to 5 or more, you can display all daily trends (30).

qiita_trends_widget.py


import re
import requests
import appex, ui
import os
from math import ceil, floor
import webbrowser
import pickle
import time

COLS = 1
ROWS = 3
fontsize = 12

def get_trend():
	trends = []
	text = requests.get( 'https://qiita.com/').text
	titles = re.findall('title":".{10,100}?",',text)
	urls = re.findall('uuid":".{10,50}?",',text)
	for i in range(30):
		trends.append({'title':'', 'url':''})
		trends[i]['title'] = titles[i][18:-7]
		trends[i]['url'] = 'https://qiita.com/items/'+urls[i][17:-7]
	trends.append({'lastUpdate':time.time()})
	with open("trends.pickle", "wb") as f:
			pickle.dump(trends, f)
	return trends


class LauncherView (ui.View):
	def __init__(self, shortcuts, *args, **kwargs):
		row_height = 110 / ROWS
		super().__init__(self, frame=(0, 0, 300, ceil(len(shortcuts[:-1]) / COLS) * row_height), *args, **kwargs)
		self.buttons = []
		for s in shortcuts[:-1]:
			btn = ui.Button(title=' ' + s['title'], name=s['url'], action=self.button_action, bg_color='#73c239', tint_color='#fff', corner_radius=7, font=('<System-Bold>',fontsize))
			self.add_subview(btn)
			self.buttons.append(btn)
	
	def layout(self):
		bw = (self.width - 10) / COLS
		bh = floor(self.height / ROWS) if self.height <= 130 else floor(110 / ROWS)
		for i, btn in enumerate(self.buttons):
			btn.frame = ui.Rect(i%COLS * bw + 5, i//COLS * bh, bw, bh).inset(2, 2)
			btn.alpha = 1 if btn.frame.max_y < self.height else 0
		
	def button_action(self, sender):
		webbrowser.open(sender.name)

def main():
	widget_name = __file__ + str(os.stat(__file__).st_mtime)
	v = appex.get_widget_view()
	if v is None or v.name != widget_name:
		try:
			with open("trends.pickle", "rb") as f:
				SHORTCUT = pickle.load(f)
		except:
			SHORTCUT = [{'lastUpdate':time.time() - 86400}]
			with open("trends.pickle", "wb") as f:
				pickle.dump(SHORTCUT, f)
		SHORTCUTS = get_trend() if time.time() - SHORTCUT[-1]['lastUpdate'] > 1800 else SHORTCUT #1800 seconds from the last time(Half an hour)Update after the above
		v = LauncherView(SHORTCUTS)
		v.name = widget_name
		appex.set_widget_view(v)

if __name__ == '__main__':
	main()

Summary

** Pythonista3 is good ** (I hope more packages can be used ...)

Recommended Posts

[IOS] I made a widget that displays Qiita trends in Pythonista3. [Python]
I made a payroll program in Python!
A memo that I wrote a quicksort in Python
I made a web application in Python that converts Markdown to HTML
I made a Discord bot in Python that translates when it reacts
I made a Caesar cryptographic program in Python.
I made a Python Qiita API wrapper "qiipy"
I made a familiar function that can be used in statistics with Python
In Python, I made a LINE Bot that sends pollen information from location information.
I made a prime number generation program in Python
I made a VM that runs OpenCV for Python
I made a prime number generation program in Python 2
I made a python text
I made a simple typing game with tkinter in Python
I made a quick feed reader using feedparser in Python
I tried "a program that removes duplicate statements in Python"
I made a puzzle game (like) with Tkinter in Python
I made a Line-bot using Python!
I made a fortune with Python.
I made a daemon with Python
[Python] I made a Line bot that randomly asks English words.
[Python3] I made a decorator that declares undefined functions and methods.
I made a package that can compare morphological analyzers with Python
I made a program that solves the spot the difference in seconds
I made a shuffle that can be reset (reverted) with Python
I made a library that adds docstring to a Python stub file.
[python] I made a class that can write a file tree quickly
I made a garbled generator that encodes favorite sentences from UTF-8 to Shift-JIS (cp932) in Python
I made a character counter with Python
I made a Hex map with Python
After studying Python3, I made a Slackbot
I created a password tool in Python.
I made a roguelike game with Python
I made a simple blackjack with Python
I made a configuration file with Python
I made a neuron simulator with Python
[Python] I made a decorator that doesn't seem to have any use.
I tried to develop a Formatter that outputs Python logs in JSON
[Python] I made a utility that can access dict type like a path
I made a Chrome extension that displays a graph on an AMeDAS page
I made a script in python to convert .md files to Scrapbox format
I made a tool that makes decompression a little easier with CLI (Python3)
I made a program to check the size of a file in Python
I made a module PyNanaco that can charge nanaco credit with python
I made a python dictionary file for Neocomplete
I made a competitive programming glossary with Python
I made a weather forecast bot-like with Python.
I made a GUI application with Python + PyQt5
I tried to create a class that can easily serialize Json in Python
I made a Line Bot that uses Python to retrieve unread Gmail emails!
I want to create a window in Python
I want to create a priority queue that can be updated in Python (2.7)
I tried playing a typing game in Python
I made a Twitter fujoshi blocker with Python ①
I wrote a class in Python3 and Java
I made a Docker image that can call FBX SDK Python from Node.js
A program that removes duplicate statements in Python
[Python] I made a Youtube Downloader with Tkinter.
[Beginner] What happens if I write a program that runs in php in Python?
[Python] I made a LINE Bot that detects faces and performs mosaic processing.
I made a module in C language to filter images loaded by Python